Search code examples
javascripthtmljquerycssswap

Swap 3 divs and make the selection div go to the center


I have three divs and I want that every single time I click on any div, it will be swapped with a second div which is meant to be at the center.

I have tried like this and it doesn't work:

function swapDiv(event, elem) {
  elem.parentNode.insertBefore(elem, elem.parentNode.secondChild);
}
<div class="all-div-container">
  <div class="div1" onclick="swapDiv(event,this);">
    1
  </div>
  <div class="div2" onclick="swapDiv(event,this);">
    2
  </div>
  <div class="div3" onclick="swapDiv(event,this);">
    3
  </div>
</div>

1 2 3 and when I click 3 the result must be 1 3 2 from this result and I click on 1 it's must be 3 1 2


Solution

  • function swapDiv(event, elem) {
        // get all elements in .all-div-container
        const allElements = [...elem.parentElement.children];
        // get index of target elem
        const targetIndex = allElements.indexOf(elem);
        // get center element
        const centerElem = allElements[1];
        // exit from function if we clicked at center elem
        if (elem === centerElem) return;
        // move center element
        if (targetIndex === 0) {
            elem.parentElement.prepend(centerElem)
        } else {
            elem.parentElement.append(centerElem)
        }
    }
    <div class="all-div-container">
        <div class="div1" onclick="swapDiv(event,this);">
            1
        </div>
        <div class="div2" onclick="swapDiv(event,this);">
            2
        </div>
        <div class="div3" onclick="swapDiv(event,this);">
            3
        </div>
    </div>