Javascript Delayed Hiding of an Element, Delayed Function Calls in Different Contexts

I was working on a small “speech bubble” library, and needed to delay hiding of the bubble. It’s not that it was required, but it was a pain in the butt figuring out how to arrange the event handlers on the different elements so that you don’t end up with a situation where you get a flickering bubble because you hide the bubble, and that fires a mouseover event that, in turn, displays the bubble again. That fires a mouseout event that causes the bubble to be hidden.

The usual right way to fix this is to detect the mouse moving into the area around the hotspot, and when it does that, hide it. My cheap fix is to just delay the hiding, and if the mouse happens to enter another element that requires the bubble to be displayed, the handler for this other element can cancel the hide.

A delay is also “nice” because it also gives the user a chance to roll back if they overshoot a target a little bit.

Here’s the code fragment to implement a delay:

[code]
var hide = function () {
this.bubble.style.display = ‘none’;
}
var delayedHide = function() {
(function (x) {
x.hideInProgress = setTimeout(function () {x.hide()},250);
})(this);
}
var cancelHide = function() {
clearTimeout(this.hideInProgress);
}
[/code]

Note how we used a closure to bind x to this, and then call x.hide() 250 ms later.

Leave a Reply