Starkers
Starkers

Reputation: 10541

Two events fire the same function

This anonymous function is fired by mouse movement.

var timeout;

// onkeypress

document.onmousemove = function(){
  clearTimeout(timeout);
  timeout = setTimeout(function(){alert("move your mouse");}, 1000);
}

Can I get it to be fired on key press as well? Or is the only way to do this efficiently defining the function as a named function and calling it like this:

document.onmousemove.namedfunction();
document.onkeypress.namedfunction();

JSFIDDLE

Upvotes: 1

Views: 76

Answers (2)

Brad
Brad

Reputation: 163234

You could leave it anonymous...

document.onmousemove = document.onmousemove = function(){

But, I wouldn't.

Upvotes: 0

Matt Bryant
Matt Bryant

Reputation: 4961

You can do it almost the same way you're doing it right now:

var timeout;

document.onmousemove = document.onkeypress = function(){
  clearTimeout(timeout);
  timeout = setTimeout(function(){alert("move your mouse");}, 1000);
}

However, reusing the same function multiple times is probably justification for giving it a name and just referencing it.

Upvotes: 1

Related Questions