Home > OS >  Swap 3 divs and make the selection div go to the center
Swap 3 divs and make the selection div go to the center

Time:05-14

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 >
  <div  onclick="swapDiv(event,this);">
    1
  </div>
  <div  onclick="swapDiv(event,this);">
    2
  </div>
  <div  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

CodePudding user response:

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 >
    <div  onclick="swapDiv(event,this);">
        1
    </div>
    <div  onclick="swapDiv(event,this);">
        2
    </div>
    <div  onclick="swapDiv(event,this);">
        3
    </div>
</div>

CodePudding user response:

Consider the following.

$(function() {
  $(".all-div-container > div").click(function(event) {
    if ($(this).index() == 0) {
      return false;
    }
    var $prev = $(this).prev();
    var $self = $(this).detach();
    $prev.before($self);
  });
});
.all-div-container>div {
  height: 2em;
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 3px;
  margin-bottom: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
</div>

You did not clarify what should happen if the first item is clicked. This code will swap the clicked element and the previous element.

  • Related