JQuery dropdown - clearTimeout, setTimeout
HTML:
<ul class="topnav">
<li><a href="#"><span>One</span></a></li>
<li><a href="#"><span>Two</span></a></li>
<li>
<li><a href="#"><span>Three</span></a></li>
<ul class="subnav">
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
</ul>
</li>
</ul>
JQuery
var timeout = null;
$(document).ready(function() {
$("ul.topnav li").mouseover(function() {
if (timeout) clearTimeout(timeout);
$(this).find("ul.subnav").slideDown('fast').show();
}).mouseout(function() {
timeout = setTimeout(closemenu, 500);
});
// sub menu mouseovers keep dropdown open
$("ul.subnav li").mouseover(function() {
if (timeout) clearTimeout(timeout);
}
).mouseout(function() {
timeout = setTimeout(closemenu, 500);
// alert(timeout);
});
// any click closes
$(document).click(closemenu);
});
// Closes all open menus
function closemenu() {
$('ul.subnav:visible').hide();
if (timeout) clearTimeout(timeout);
}
I have a timeout problem. When used, if I mouseover "Three", the dropdown menu remains forever. if I mouseover "A", the drop-down menu will stay forever, but if I attach "B" or anything below, the menu will close on me. if you uncomment "// alert (timeout)"; it gets there for B, (and A), but the wait time will matter. Why is this? I thought clearTimeout would ignore the timeout variable?
+3
2 answers
You can simplify the code as a whole by using .hover()and .data():
$(function() {
$("ul.topnav li").hover(function() {
var timeout = $(this).data("timeout");
if(timeout) clearTimeout(timeout);
$(this).find("ul.subnav").slideDown('fast');
}, function() {
$(this).data("timeout", setTimeout($.proxy(function() {
$(this).find("ul.subnav").slideUp();
}, this), 500));
});
$(document).click(function() {
$('ul.subnav:visible').hide();
});
});β
, timeout, - <li>, , , . , .hover() mouseenter mouseleave, mouseover mouseout, , , mouseenter , mouseleave parent <li> .
, , , . $.proxy, this , , to ( this)... , .
+5