Search code examples
javascripteventsbuttonclickmove

JavaScript transfering one element to another (multiple times) by using event


I want to transfer multiple times after click on "przenieś" the whole li from one div class="listContainer two" to another, and back again (and again) using JavaScript. How should I prepare the JavaScript code for the most efficient way?

<div class="listContainer two">
  <ul id="list1">
    <li>Item 1 z listy 1 <a class="moveBtn">Przenieś</a></li>
    <li>Item 2 z listy 1 <a class="moveBtn">Przenieś</a></li>
  </ul>
</div>

<div class="listContainer two">
  <ul id="list2">
    <li>Item 1 z listy 2 <a class="moveBtn">Przenieś</a></li>
    <li>Item 2 z listy 2 <a class="moveBtn">Przenieś</a></li>
  </ul>
</div>

Solution

  • You could use something like this. It has no dependencies on jQuery, If you need it to run on older browsers you can change const to var and change matches to checking the targets className.

    const list1 = document.querySelector('#list1')
    const list2 = document.querySelector('#list2')
    
    const swapListItem = function(e) {
      // only continue execution if the target is a .moveBtn
      if (e.target.matches('.moveBtn')) {
        e.preventDefault()
        const item = e.target.parentNode
        const parent = item.parentNode
        parent.removeChild(item)
        if (parent === list1) {
          list2.appendChild(item)
        }
        else {
          list1.appendChild(item)
        }
      }
    }
    // bind a single event to the window
    window.addEventListener('click', swapListItem, false)
    body { font-family: sans-serif }
    .list { width 40%; float: left; padding: 0; list-style-type: none; color: white }
    li { padding: 0.5em }
    #list1 { background: #BADA55 }
    #list2 { background: #1CE1CE }
    <ul class="list" id="list1">
        <li>Item 1 z listy 1 <a href="#" class="moveBtn">Przenieś</a></li>
        <li>Item 2 z listy 1 <a href="#" class="moveBtn">Przenieś</a></li>
    </ul>
    
    <ul class="list" id="list2">
        <li>Item 1 z listy 2 <a href="#" class="moveBtn">Przenieś</a></li>
        <li>Item 2 z listy 2 <a href="#" class="moveBtn">Przenieś</a></li>
    </ul>