user2270134
user2270134

Reputation: 99

Javascript hide with delay

I've got some troubles with setTimeOut, i want to delay the hide of the submenu, but its not working at all.. :-(

I put the working line inside comments. What i have done wrong?

        $('ul.menu').find('li').mouseover(function() {
           $(this).children('ul, .mega-menu').css('display','block');

        }).mouseout(function() {
           setTimeout(this.children('ul, .mega-menu').style.display="none",4000); 
           /* $(this).children('ul, .mega-menu').css('display','none'); */
        });

Thanks for any help or ideas!

Upvotes: 2

Views: 193

Answers (4)

Sharique Hussain Ansari
Sharique Hussain Ansari

Reputation: 1456

Please use this to hide with delay:-

$('ul.menu').find('li').delay(4000).fadeOut();   

This will wait for 4 sec then hide

To show use this:-

$('ul.menu').find('li').delay(6000).fadeIn();

So you can write like this:-

$(document).ready(function(){    
  $('ul.menu').find('li').hover(function() {
     var $megamenu = $(this).children('ul, .mega-menu'); 
     $megamenu.show();   
  },function() {
    var $megamenu = $(this).children('ul, .mega-menu');  
    $megamenu.delay(4000).fadeOut(); 
 });
});

you can also use fadeOut(1000) for animation effect.

If you want to use setTimeout you can use Dave Salomon answers or this:-

$(document).ready(function(){    
  $('ul.menu').find('li').hover(function() {
     var $megamenu = $(this).children('ul, .mega-menu'); 
     $megamenu.show();   
  },function() {
    var $megamenu = $(this).children('ul, .mega-menu');  
    setTimeout(function(){$megamenu.hide()},"4000"); 
 });
});

Hope this will help.

Upvotes: 1

Dave Salomon
Dave Salomon

Reputation: 3287

Your scope in your setTimeout(function(){...}); isn't the same as the rest of the method. i.e. this is different.

Also, your code is a bit wonky.

$('ul.menu').find('li').mouseover(function() {
    var $submenu = $(this).children('ul, .mega-menu');
    $submenu.css('display','block');
}).mouseout(function() {
    var $submenu = $(this).children('ul, .mega-menu');
    setTimeout(function(){
        $submenu.hide();
    }, 4000);
});

http://jsfiddle.net/daveSalomon/hLk0s0bd/

Upvotes: 0

Griffith
Griffith

Reputation: 3217

You need to pass either a function (and not calling it) or code to setTimeout's first parameter. Try:

var that = this;
setTimeout(function(){
    that.children('ul, .mega-menu').style.display="none";
}, 4000); 

Upvotes: 0

Ruben  Yeghikyan
Ruben Yeghikyan

Reputation: 497

Try this.

$('ul.menu').find('li').mouseover(function() {
    $(this).children('ul, .mega-menu').show();
}).mouseout(function() {
    $(this).children('ul, .mega-menu').hide(4000);     
});

Upvotes: 0

Related Questions