jquery - Why is setTimeout not working with .hover()? -


jsfiddle: http://jsfiddle.net/yl1uu0hv/

i'm trying create simple hoverintent using settimeout. i'm not sure problem provided code. if comment out hovertimer = settimeout(function(){ , }, 500); addclass i'm using works. if aforementioned items active (not commented out), addclass doesn't work.

i'm getting kind of error due syntax of $('ul#megamenulist li').each($(this).addclass(opts.mmactiveclass.mmclassname)); , keeps bubbling doing nothing.

what's supposed happen after x milliseconds of hovering on item, class 'active' supposed added hovered 'li' tag. if not hovered on x milliseconds or longer, 'active' not added. and, if 'active' added, on mouseleave class 'active' should removed.

any appreciated.

jquery(document).ready(function($){         $('ul#megamenulist li').hover(             function(){                 console.log('over');                 //hovertimer = settimeout(function(){                     $('ul#megamenulist li').each($(this).addclass('active'));                 //}, 500);              },             function(){                 console.log('off');                 cleartimeout(hovertimer);                 $('ul#megamenulist li').removeclass('active');             }         ); });   <div id="megamenunav">     <ul id="megamenulist">         <li>             <a href="#"><span>explore</span></a>         </li>         <li>             <a href="#"><span>develop</span></a>         </li>         <li>             <a href="#"><span>engage</span></a>         </li>         <li>             <a href="#"><span>shop</span></a>         </li>         <li>             <a href="#"><span>about</span></a>         </li>     </ul> </div> 

the problem context inside settimeout function (this keyword) global window object. simplest fix save reference ul#megamenulist li element in variable , use inside settimeout.

correct code:

var $li = $('ul#megamenulist li').hover(     function () {         var self = this;         hovertimer = settimeout(function(){             $(self).addclass('active');         }, 500);     },     function () {         cleartimeout(hovertimer);         $li.removeclass('active');     } ); 

also it's practice cache jquery collections avoid repetitive dom queries. example can cache in code above, since hover returns collection.

demo: http://jsfiddle.net/yl1uu0hv/2/


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -