Question

In my page I have different menu items that trigger different corresponding pictures. The z-index switches the corresponding picture to the top. Here is the code:

$(document).ready(function(){

var doorOpen = false;

$("a[href=#andrew]").click(function() {

    if (doorOpen) { // set animation duration for door close, based on actually needed to animate the door closed or not
        var duration = 1500;
    } else {
        var duration = 0;
    }

    $("#rightdoor,#leftdoor").animate(
        {"marginLeft":"0px"},
        {duration:duration,
            complete:function() {
                $('.pic2 .pic3 .pic4 .pic5').css('zIndex', 1);  //puts wrong pics in back
                $('.pic1').css('zIndex', 2);  //brings right pic into view
                $('#rightdoor').animate({  //opens doors again
                 marginLeft: "150px",
                }, 1500);
                $('#leftdoor').animate({
                 marginLeft: "-150px",
                }, 1500);
            }
        }
    );

    doorOpen = true;


});

$("a[href=#bugz]").click(function() {

    if (doorOpen) { // set animation duration for door close, based on actually needed to animate the door closed or not
        var duration = 1500;
    } else {
        var duration = 0;
    }

    $("#rightdoor,#leftdoor").animate(
        {"marginLeft":"0px"},
        {duration:duration,
            complete:function() {
                $('.pic1 .pic3 .pic4 .pic5').css('zIndex', 1);  //puts wrong pics in back
                $('.pic2').css('zIndex', 2);  //brings right pic into view
                $('#rightdoor').animate({  //opens doors again
                 marginLeft: "150px",
                }, 1500);
                $('#leftdoor').animate({
                 marginLeft: "-150px",
                }, 1500);
            }
        }
    );

    doorOpen = true;    
});
});

The problem is that the z-index works but only once per menu item it seems. If you initially click #andrew, it brings pic1 to the top and if you click #bugz it brings pic2 to the top. However, if you click #andrew again it animates the code before and after the .css(z-index) change but does not change the z-index to bring pic1 back to the top.

I am new to Javascript/JQuery so please forgive me if I am missing something obvious

Was it helpful?

Solution

Your selector is wrong: $('.pic2 .pic3 .pic4 .pic5') looks for descendants of .pic2.

You could use commas to separate those classes instead of spaces, but it's simpler to use the .siblings method instead:

$('.pic1').css('zindex',2).siblings().css('zindex',1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top