Detect if mouse is touching element using Prototype.js?

410 Views Asked by At

I am attempting to make an Javascript application where an element will slowly fade out when the mouse is touching it and fade in when the mouse is off the element. I'm using Prototype with Scriptaculous, so is there a Prototype function that can tell me whether or not the mouse is touching an object at any given time?

My main problem using Scriptaculous FadeOut/FadeIn effects is that when one is triggered before the other has finished, the effects conflict and the element misbehaves.

1

There are 1 best solutions below

3
On

Just store the effect object somewhere (for instance in a closure), and cancel it when you want to apply a different effect

var element = $("element"),
    currentEffect = null;

element.observe("mouseenter", function() {
    if (currentEffect) {
        currentEffect.cancel();
    }
    currentEffect = new Effect.Fade(element);
});

element.observe("mouseleave", function() {
    if (currentEffect) {
        currentEffect.cancel();
    }
    currentEffect = new Effect.Appear(element);
});

jsfiddle demo

(obviously you can refactor that in several ways, but basically all you need to do is observer the mouseenter and mouseleave events, and remember to cancel any running effect before starting a new one)