HagelslagBMB HagelslagBMB - 7 months ago 12
Javascript Question

Why is this else statement not triggered?

I've been trying to get a div to get behind another div on one click and on top of the div on the next click. So for example when div1 is behind div2 and you click div1 it should appear in front of div2. When you click div1 again (which is now in front of div2) it should get behind div2 again.

I'm trying to look up the z-index of the div and decide wether the the z-index should be higher or lower with an if/else statement. But for some reason the else isn't being triggered, it only seems to run the if statement.

The jsfiddle

The code below is where I'm trying to look up whether the z-index is lower or higher then 5 (they can only be 0 or 10 but this seemed like a good foolproof method to do the check). The problem is that even when the z-index is turned into 10 that the ifstatement is still getting executed instead of the else.

if ($(".div1").css("z-index") < "5") { //is z-index smaller then 5? make it 10
$(".div1").click(function() {
$(this).css('z-index', '10');
console.log('block1 if');
});
} else { //is z-index bigger then 5? make it 0
$(".div1").click(function() {
$(this).css('z-index', '0');
console.log('block1 else');
});
}


I'm totally lost as to what the problem is so all help is welcome.
And thanks for taking the time to read my question!

Answer

I don't know if this fixes your problem, but i think you should move your if/else inside a single click event. Also like other people stated, you need to compare to an int and not a string

  $(".div1").click(function() {
      if ($(this).css("z-index") < 5)
      {
        $(this).css('z-index', '10');
      }
      else{
        $(this).css('z-index', '0');
      }
      console.log($(this).css('z-index'));
   });