I think it’s got something to do with the nested functions, but they need to be this way. Why isn’t it working? Am I doing something stupid? This is an isolated example and I must be using $(this), so it seems I have to nest the functions?
HTML:
<div class="box"></div>
<ul>
<li>Hover box, it turns blue. Leave box, it turns red after 2 secs.</li>
<li>If you hover back onto box before 2 secs is up, it's supposed to clear timer and keep box blue.</li>
<li>It doesn't clear timer and after 2 secs the box still turns red. Why?</li>
</ul>
JavaScript:
var t;
$('.box').on('mouseenter', function() {
$thisBox = $(this);
clearTimeout(t);
$thisBox.addClass('blue');
$thisBox.on('mouseleave', function() {
t = setTimeout(function() { $thisBox.removeClass('blue'); }, 2000);
})
});
JSFiddle: http://jsfiddle.net/ddbtZ/7/
Thanks for looking 🙂
http://jsfiddle.net/ddbtZ/3/
Your
.on()shouldn’t be nested. Effectively, that’s attaching a new handler for every time you hover over the element.EDIT: As per question clarification.
Use
.one()instead of.on()http://jsfiddle.net/ddbtZ/8/