views:

282

answers:

1

I wish to do something like as follows:

  • When the mouse goes over to some element, record it
  • If the mouse stays there for 3 seconds, then execute some action f() for that element
  • If the mouse leaves that element before 3 seconds, then the action should not be executed.

How can I implement this delayed execution with possible cancellation? An answer using DOJO library would be nicer since I am using DOJO toolkit in my project.

+2  A: 

Try the following:

var delay = 3000;

dojo.forEach(dojo.query(".some-element-set"), function(element) {
    dojo.connect(element, "onmouseover" function() {
        // dojo.partial(f, this.id) will apply `this.id` to `f`, but it 
        // will not execute it and will only a new function
        this._timer = setTimeout(dojo.partial(f, this.id), delay);
    });

    dojo.connect(element, "onmouseout" function() {
        // this._timer was set as an element attribute in the above event 
        // handler so we don't have to keep track of them separately in 
        // some silly array/object
        clearTimeout(this._timer);
    });
});

See the query, forEach, connect and partial documentation for more information.

Edit: I've update my answer per the OP's comment

Justin Johnson
This looks great. I guess I need a more generalized version of this. I have a set of elements (each with distinct id), and I need to invoke the function f with the id of the element. Would that be too difficult?
Shailesh Kumar
I've edited my answer. Take a look.
Justin Johnson
Thanx.. This rocks :)
Shailesh Kumar
Sure thing mate
Justin Johnson