Home > Net >  Change the order of elements onclick
Change the order of elements onclick

Time:10-18

I have a simple slider, and I want to change the order of the elements inside the slider container depending on which single slide the user clicks, for example when the user clicks on the left or the right slide it moves to the center, so the active slide is always on center, and I think by reordering the slides each time the user clicks is a good way to do that, but if you have any other way to do that, please let me know, I will be grateful.

I only want to use Javascript and HTML, not jquery or something like that.

Here's the code that I used to reach that but it doesn't work:

<div >
    <div > a </div> 
    <div > b </div> 
    <div > c </div> 
</div>
// slider
let slider = document.querySelector('.slider');
let items = document.querySelectorAll('.slider .slide');
items.forEach((element , index) => {
    element.onclick = function () {
        let arr = [0,2,1];
        let elements = document.createDocumentFragment();
        arr.forEach(idx => {
            elements.appendChild(items[idx].cloneNode(true));
        });
        slider.innerHTML = null;
        slider.appendChild(elements);
    }
});

CodePudding user response:

You may do it by this way.

This solution works for any number of element you have in the slider container. However there's a drawback where if the number of child element are even number, then it will not have the "center" position in this case.

const slider = document.querySelector('.slider');
const items = document.querySelectorAll('.slider .slide');
let arrayOfElements = [];

const itemOnClick = (el) => {
  const totalItem = items.length - 1; //get total items
  const centerIndex = (totalItem / 2).toFixed(0); //center index
  
  //Creating a loop effect where the order of slide will always be a,b,c,d,e when changing the center element
  while(arrayOfElements[centerIndex] !== el){
    const popped = arrayOfElements.pop();
    arrayOfElements.unshift(popped);
  }
  slider.innerHTML = "";
  for(let i=0;i<arrayOfElements.length;i  ){
    slider.appendChild(arrayOfElements[i]);
  }
}

items.forEach((el) => {
  arrayOfElements.push(el); //create an array containing the slide
  el.onclick = () => {
    itemOnClick(el);
  };
});
.slider{
  display: flex;
  flex-direction: row;
}

.slider .slide{
  margin: 0 10px;
  padding: 5px;
  cursor: pointer;
  border: 1px solid gray;
}
<div >
    <div > a </div> 
    <div > b </div> 
    <div > c </div> 
    <div > d </div> 
    <div > e </div> 
</div>

  • Related