Move Items in Ul Li Up and Down

Move items in Ul Li up and down

You can try something like the following:

$('.upbutton').on('click', function () {
var hook = $(this).closest('.liEllipsis').prev('.liEllipsis');
var elementToMove = $(this).closest('.liEllipsis').detach();
hook.before(elementToMove);
});
$('.downbutton').on('click', function () {
var hook = $(this).closest('.liEllipsis').next('.liEllipsis');
var elementToMove = $(this).closest('.liEllipsis').detach();
hook.after(elementToMove);
});

https://jsfiddle.net/16sebrjq/

If you want to move using a button outside, and a selected li element, try something like this:

$('.liEllipsis').on('click', function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
});

$('.upbutton').on('click', function () {
var $currentElement = $('#ul_li_SubCategories .selected');
moveUp($currentElement);
});

$('.downbutton').on('click', function () {
var $currentElement = $('#ul_li_SubCategories .selected');
moveDown($currentElement);
});

var moveUp = function ($currentElement) {
var hook = $currentElement.prev('.liEllipsis');
if (hook.length) {
var elementToMove = $currentElement.detach();
hook.before(elementToMove);
}
};

var moveDown = function ($currentElement) {
var hook = $currentElement.next('.liEllipsis');
if (hook.length) {
var elementToMove = $currentElement.detach();
hook.after(elementToMove);
}
};

https://jsfiddle.net/16sebrjq/1/

Can I use jQuery to easily shift li elements up or down?

It's actually not that hard. JQuery almost gets you there by itself with the insertBefore and insertAfter methods.

function moveUp($item) {
$before = $item.prev();
$item.insertBefore($before);
}

function moveDown($item) {
$after = $item.next();
$item.insertAfter($after);
}

You could use these like

moveDown($('#menuAbout'));

and the menuAbout item would move down.

If you wanted to extend jQuery to include these methods, you would write it like this:

$.fn.moveUp = function() {
before = $(this).prev();
$(this).insertBefore(before);
};

$.fn.moveDown = function() {
after = $(this).next();
$(this).insertAfter(after);
};

and now you can call the functions like

$("#menuAbout").moveDown();

JavaScript: Move elements up and down in the list

Hope this helps:

window.onload = function () { var upLink = document.querySelectorAll(".up");
for (var i = 0; i < upLink.length; i++) { upLink[i].addEventListener('click', function () { var wrapper = this.parentElement;
if (wrapper.previousElementSibling) wrapper.parentNode.insertBefore(wrapper, wrapper.previousElementSibling); }); }
var downLink = document.querySelectorAll(".down");
for (var i = 0; i < downLink.length; i++) { downLink[i].addEventListener('click', function () { var wrapper = this.parentElement;
if (wrapper.nextElementSibling) wrapper.parentNode.insertBefore(wrapper.nextElementSibling, wrapper); }); }}
<ul> <li>1 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li> <li>2 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li> <li>3 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li> <li>4 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li> <li>5 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li> <li>6 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li></ul>

Moving all elements up one and down level

If I understand correctly, you only ever need to move one item.

When .next is clicked, take the last item and move it to the first position using .prependTo().

When .prev is clicked, take the first item and move it to the last position using .appendTo().

$(document).ready(() => {    $(".prev").on("click", () => {        $("ul > li").first().appendTo("ul");    });      $(".next").on("click", () => {        $("ul > li").last().prependTo("ul");    });});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="prev">Previous</button>
<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li></ul>
<button class="next">Next</button>

How would I move an li to the bottom of a ul?

You could simply use before() to do that as well by referencing the node (li) you want to add before it to.

Live Demo:

function add_option(optionname) {
var listItem = document.createElement("li");
var removeButton = document.createElement("button");
var optionSpan = document.createElement("span");

listItem.className = "role_box_role";
listItem.style = "border-color: rgb(255, 0, 0);";

//removeButton.type = "button";
removeButton.innerText = "-";
removeButton.className = "role_remove_button";
removeButton.style = "background-color: rgb(255, 0, 0);";

optionSpan.innerText = optionname;
listItem.appendChild(removeButton);
listItem.appendChild(optionSpan);

// Get reference node
var referenceNode = document.querySelector('#plusbutton');

// Add the new node before the reference node
referenceNode.before(listItem);
}
<ul class="role_box_roles" id="rbroles">
<li class="role_box_role" style="border-color: rgb(255, 0, 0);">
<button class="role_remove_button" type="button" style="background-color: rgb(255, 0, 0);">-</button>
<span>Staff</span>
</li>
<li id="plusbutton"><button class="role_add" type="button" onclick="show_options()">+</button></li>
</ul>


<button onclick="add_option('Blah')">
Add
</button>

How to move a list item to a specified index(position) in an unordered list using Javascript

I would use a constructor with an index based method for this:

function LiMover(liParent){  this.kids = liParent.children;  this.move = (index, beforeIndex = null)=>{    const k = this.kids, e = k[index];    if(beforeIndex === null){      liParent.appendChild(e)    }    else{      liParent.insertBefore(e, k[beforeIndex]);    }    return this;  }}const liMover = new LiMover(document.querySelector('ul'));liMover.move(0); // move 0 index (one) after last indexliMover.move(5, 0); // move 5 index (one) back to 0 indexliMover.move(1, 4); // move 1 index (two) to 4 indexliMover.move(3, 5).move(2, 0); // showing return this chain
<ul>  <li>one</li>  <li>two</li>  <li>three</li>  <li>four</li>  <li>five</li>  <li>six</li>  </ul>

Javascript issue with moving list items up and down

If you check the browser's console (F12 to open Dev Tools in most browsers) you'll see an error like this:

Uncaught TypeError: Cannot read property 'nextElementSibling' of null

That's because on this line:

li.nextElementSibling.nextElementSibling;

...the last element's .nextSibling is null (it doesn't have a next sibling). You need to test for null rather than just chaining an extra .nextElementSibling on the end:

    var ul = document.querySelector('ul');        ul.addEventListener('click', (e) => {     let clicked = e.target;     let li  = clicked.parentNode;     let next    = li.nextElementSibling;               // <-- Code changed        if (next != null) next = next.nextElementSibling;  // <-- Code inserted      let prev    = li.previousElementSibling;                if (clicked.className === 'down') {         ul.insertBefore(li, next);        } else if (clicked.className === 'up') {         ul.insertBefore(li, prev);        }    });
    <ul>        <li>item1 <button class="down">Move down</button><button class="up">Move up</button></li>        <li>item2 <button class="down">Move down</button><button class="up">Move up</button></li>        <li>item3 <button class="down">Move down</button><button class="up">Move up</button></li>        <li>item4 <button class="down">Move down</button><button class="up">Move up</button></li>        <li>item5 <button class="down">Move down</button><button class="up">Move up</button></li>    </ul>

how to allow moving li items in only one list?

Let's break down your code:

$item = $(".highlight");

gets all the highglighted items (assume lis only)

$before = $item.first().prev();

.first gets the first one and then the li above it

$item.insertBefore($before);

takes all the items and puts them at the before

Because $item is a collection/array of items (which is why you use .first) any actions apply to the whole array.

You could change the last line to:

$item.first().insertBefore($before);

but then only one will move up at a time.

Alternatively, work on one item at a time, eg:

$("#btn-move-up").click(function () {
$items = $(".highlight");
$items.each(function(index) {
$before = $(this).prev();
$(this).insertBefore($before);
});
});

unable to move multiple items in the list up or down in jquery

Need to select the first item of the list before inserting before, and last item before inserting after. Else it would insert before or after for every item highlighted:

$("#btn-move-up").click(function() {  $item = $(".highlight");  $before = $item.first().prev();  $item.insertBefore($before);});
//onclick of move down button, move the item down in the list$("#btn-move-down").click(function() { $item = $(".highlight"); $after = $item.last().next(); $item.insertAfter($after);});

$('ul').on("click", "li", function(e) { if ($(this).hasClass('highlight')) { $(this).removeClass('highlight'); } else {
$(this).addClass('highlight');
} e.stopPropagation();});
.highlight {  background-color: #ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button type="button" id="btn-move-up" class="btn btn-info" data-toggle="tooltip" data-placement="right" title="Up"><i class="fa fa-arrow-up"></i>Up</button>
<button type="button" id="btn-move-down" class="btn btn-info" data-toggle="tooltip" data-placement="right" title="Down"><i class="fa fa-arrow-down"></i>Down</button>
<ul id="fields"> <li>Ist</li> <li>2nd</li> <li>3rd</li> <li>4th</li></ul>

Moving list items (li) between unordered lists (ul)

Instead of binding to click on the items directly as you are doing now:

$('#one ul li').click(function(){...})

This applies when the script is loading only to contact that is matched then. Since your LI is added later (dynamically) no event is bound on that one.
You can use the .on() jQuery function to bind to a parent element specifying a scope, which will apply to any element loaded in the future:

$("#one").on("click", "ul li", function(){...})

The difference is the event is bound to #one but applies to any ul li inside it (present and future).

https://api.jquery.com/on/



Related Topics



Leave a reply



Submit