How to Copy items between lists with jQuery

Today we are going to exercise again the handling of lists with jQuery. For this we are going to see how we can copy elements between lists with jQuery.

The goal is to move items from a Source list to another Destination list. This time we will move the element we click on in the source list and add that element to the destination list.

Surely we are all intuiting that we will do the following:

  1. Define a source list and on each of its elements individually we will link the click event to them so that they react to it.
  2. Pass it a function that takes the selected item and moves it to another list with Jquery appendTo

HTML

Here is a list below.

<ul class="mainList">
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
    <li>Item4</li>
</ul>

we will assign the click event to each li element of ul

$ ('#mainList li').on('click', function(){
  $ (this).appendTo('#destinationList');
});

The .appendTo() method allows us to copy elements between lists with jQuery since it moves from the source list to the main list.

With that code it would be enough but to be sure which element we are selecting with the mouse and that it will receive the click event, we will highlight the element in orange. 

Also with jQuery onmouseout we will make it recover its original style on a white background and thus stop being highlighted.

$ ('#mainList li').on('mouseover', function () {
  $ (this).css ('background', 'orange');
});

$ ('#mainList li').on('mouseout', function () {
  $ (this).css ('background', 'white');
});

Conclusions of copying items between lists with jQuery

In this exercise we have reviewed and explained event binding, using the one method, changing the style of elements with the JQuery css function, and using click , mouseover, and mouseout events to explain how to copy elements between lists with jQuery.

Admin: