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 class="slider">
<div class="slide"> a </div>
<div class="slide"> b </div>
<div class="slide"> 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);
}
});
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.