Delay CSS function in Jquery?

Evanss picture Evanss · Feb 10, 2011 · Viewed 28.2k times · Source

How can I delay a CSS change in jquery? Here is my code:

$("document").ready(function() {
    $(".pressimage img").mouseenter(function() {
        $jq(this).css('z-index','1000');
            });
    $(".pressimage img").mouseleave(1000,function() {
        $jq(this).css('z-index','1');
            });
});

I need the mouseleave function to occur about 1/2 a second after the mouse leaves.

Im using some other jquery to make images expand on mouseover. When they expand they cover each other, so I need the z-index of the animated image to be higher than the other. Then when the mouse leaves the z-index has to return to normal.

The above code works except that the z-index changes as soon as the mouse leaves, so the animation doesn't have time to complete. I therefore need to delay the mouseleave function a bit. Thanks

UPDATE

Here is my site: http://smartpeopletalkfast.co.uk/ppr6/press

Ive put my code in the head:

 $jq("document").ready(function() {

    $jq(".pressimage img").mouseenter(function() {
        $jq(this).css('z-index','100');
            });

    $jq(".pressimage img").mouseleave(function() {
        $jq(this).css('z-index','1');
            });

});

This code is working fine but doesn't have any delay. If you hover over the top left image it works fine but as soon as you mouse off it goes behind the image below it. Thanks

Answer

Ken Redler picture Ken Redler · Feb 11, 2011

Try this:

$(".pressimage img").mouseleave( function(){
    var that = this;
    setTimeout( function(){
      $(that).css('z-index','1');
    },500);
 });