I’m trying to make a menu where there are elements shown in plain text, and when you hover over them there are fields revealed to edit the plain text.
You can see an example here: http://jsfiddle.net/Bx7vX/9/
The timer variable is declared globally, so when you hover over a second list element really quickly, it clears the timer for the previous element. However, when I declare the timer inside of the function (seen here: http://jsfiddle.net/JYavJ/), the multiple elements will fade out correctly, but when you hover off of an element and then back on, it won’t clear the timer correctly.
So basically, I’m having an issue with keeping the timer variable persistent between hovers on a single element. I’ve tried adding the timer variable to the DOM element with no success. If someone knows how to solve this issue, or maybe a better way to approach this menu style entirely, I’d much appreciate it. Thanks!
For reference, here’s the code with the timer declared outside of the hover function:
$('.diet_draggable').hover(function() {
var timer;
var current = $(this);
if (current.is(':hover')){
clearTimeout(timer);
$(this).children(".static_units").hide();
$(this).children(".mod_units").show();
}
else if (current.children('.mod_units').children('.list_amount').is(":focus")) {
current.children('.mod_units').children('.list_amount').blur(function() {
timer = setTimeout(function() {
current.children(".mod_units").fadeOut(300);
current.children(".static_units").fadeIn(300);
}, 500);
if (current.is(':hover')) clearTimeout(timer);
});
}
else {
timer = setTimeout(function() {
current.children(".mod_units").fadeOut(300);
current.children(".static_units").fadeIn(300);
}, 500);
}
});
Here you are, this version is much simpler but works exactly as you want:
};
$(‘.diet_draggable’).each(function() {
dietDraggable($(this));
});
The key is that I’m using both parameters of the jQuery hover function. The second parameter is what happens when you hover off of the element in question. The other key piece is that I’m declaring the timer inside of the function dietDraggable. This ensures that a closure is created for each of the elements and therefore they each have their own timer.
To see it in action: http://jsfiddle.net/VjHcr/2/