I am fairly new to JavaScript. I have several div elements on my website that are draggable and are made to look and behave like cards on a table. When an element is clicked and dragged, its z-index changes to the topmost position while the z-indexes of the other elements are moved down 1 position. This keeps all of the elements in the correct order that they have been placed in by the user so that when they are stacked and moved about it looks natural.
The code below works smoothly with 3 elements, in which I am manually checking and changing each zIndex value using if statements, but this method becomes exponentially more complicated as I add more draggable elements (the plan is to have at least 10). I wish I could just subtract 1 from the zIndex of all other draggable elements. I can't because zIndex is a string value not a number. Is there a way around this? A way of treating string values as numbers so I can perform arithmetic maybe? Any help would be greatly appreciated.
Note: the code below is part of an element dragging function that specifically deals with the element "card1", I haven't included the whole thing as this is the only part that deals with zIndex
//change the zIndexes when card1 is moved
elmnt.style.zIndex = "3"; //places card1 on top
//check zIndex positions of card2 and card3 and lower them by 1
if (document.getElementById("card2").style.zIndex == "3"){
if (document.getElementById("card3").style.zIndex == "2"){
document.getElementById("card3").style.zIndex = "1";
document.getElementById("card2").style.zIndex = "2";
}
else {
document.getElementById("card2").style.zIndex = "2";
}
}
if (document.getElementById("card3").style.zIndex == "3"){
if (document.getElementById("card2").style.zIndex == "2"){
document.getElementById("card2").style.zIndex = "1";
document.getElementById("card3").style.zIndex = "2";
}
else {
document.getElementById("card3").style.zIndex = "2";
}
}