Search code examples
javascriptcarouselz-index

Using JS to change three div IDs (carousel-esque), works twice, but then skips a div


I'm trying to create a carousel where all three items are visible, and they switch position when the navigation is clicked (at the moment only working on the left arrow).

I am doing this by assigning each div to a position using an id, and using JS to change the ids.

It works as intended, but when #pos3 (the banana) becomes #pos1, it for some reason gets skipped, and #pos2 and #pos3 just exchange places.

The CSS:

#pos1{
left:10%;
}

#pos2{
left:30%;
z-index:2;
top:50px;
background:rgba(255,255,255,0.9);
}

#pos3{
left:60%;
}

The JS

document.getElementById("left").onclick = function (){
  document.getElementById("pos2").setAttribute("id", "pos1");
  document.getElementById("pos3").setAttribute("id", "pos2");  
  document.getElementById("pos1").setAttribute("id", "pos3");    
}; 

Fiddle here


Solution

  • document.getElementById("pos2").setAttribute("id", "pos1"); document.getElementById("pos3").setAttribute("id", "pos2");
    document.getElementById("pos1").setAttribute("id", "pos3");

    By the time third line is executed, pos1 doesn't exist as you've already changed that on 1st line.

    Simply introduce a temporary id to fix this.

    document.getElementById("pos1").setAttribute("id", "temp"); document.getElementById("pos2").setAttribute("id", "pos1"); document.getElementById("pos3").setAttribute("id", "pos2");
    document.getElementById("temp").setAttribute("id", "pos3");