1

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";
        }
    }
  • 3
    so change it to a number before you add one. – epascarello May 05 '20 at 14:09
  • You can assign a number to zIndex – acbay May 05 '20 at 14:15
  • Read [Convert a string to an integer?](https://stackoverflow.com/questions/1133770/convert-a-string-to-an-integer) and [What's the best way to convert a number to a string in JavaScript?](https://stackoverflow.com/questions/5765398/whats-the-best-way-to-convert-a-number-to-a-string-in-javascript) – Turnip May 05 '20 at 14:17
  • If you subtract from a string it will be converted to a number automatically. Only addition needs special handling, because `+` performs concatenation with strings. – Barmar May 05 '20 at 14:21
  • @Turnip thank you, that was helpful – Adam A Mandelbrot May 05 '20 at 14:54

0 Answers0