user1160232
user1160232

Reputation: 98

Make image's z-index change on click

I've tried a lot of things, but nothing is working.

When I click on an mage, I want it's z-index to be "9999". When I click to show another image, I want the previous image's z-index to go back to "0".

So basically, I only want one image to show at a time - I want a specific function to run for each image.

http://jsfiddle.net/WarrenBee/a78R7/

PLEASE help me!

Upvotes: 1

Views: 1091

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074809

Just remember the last image and value and put the old value back:

var lastImage, lastZIndex;
$('.char').click(function () { 
    var thisImage = $(this).children('img');
    if (lastImage) {
        lastImage.css('z-index', lastZIndex);
    }
    lastImage = thisImage;
    lastZIndex = thisImage.css('z-index');
    thisImage.css({'z-index' : '9999'})
});

Updated fiddle

Ideally, avoid creating global variables by wrapping all of that in a function:

(function() {
    var lastImage, lastZIndex;
    $('.char').click(function () { 
        var thisImage = $(this).children('img');
        if (lastImage) {
            lastImage.css('z-index', lastZIndex);
        }
        lastImage = thisImage;
        lastZIndex = thisImage.css('z-index');
        thisImage.css({'z-index' : '9999'})
    });
})();

Further updated fiddle

Upvotes: 0

Timm
Timm

Reputation: 12753

Change your JavaScript to this:

$('.char').click(function () {
    $('.char img').css({'z-index' : '0'});
    $(this).children('img').css({'z-index' : '9999'});
});

This will set the z-index of all imgs inside a char class back to 0, before setting the one that was clicked to 9999.

Upvotes: 1

Related Questions