If i'm writing event in this way, action executes when it should:
document.getElementById('myElem').onmousedown = (e) => {
console.log('fired!')
}
But if i'm writing same stuff in other way, action executes when page is loaded, once:
let HandleEvent = (event) => {
console.log('fired!')
}
document.getElementById('myElem').onmousedown = HandleEvent(event)
UPD:
Ofcourse it is just example, HandleEvent function will have much more complex logic.
My questions is:
- Why?
- How to make it work properly?
6 Answers 6
document.getElementById('myElem').onmousedown = HandleEvent;
Would do what you want; you should not execute the handler when assigning it. You should just assign the function reference.
Then you can also assign it as the onload handler, or even call it yourself (if you are not relying on the event object)
Comments
document.getElementById('myElem').onmousedown = HandleEvent;
To pass additional arguments you could use bind:
document.getElementById('myElem').onmousedown = HandleEvent.bind(null, argument1, argument2);
...or you could use a factory function:
document.getElementById('myElem').onmousedown = createHandler();
function createHandler() {
var a = calculateA();
var b = calculateA();
return function handleEvent() {
//use a and/or b
};
}
There are other ways too. Precise code will depend on your use case.
6 Comments
Function.prototype.bindYou don't need the event.
let HandleEvent = (event) => 'fired!';
document.getElementById('myElem').onmousedown = HandleEvent
Comments
Remove the event
let HandleEvent = (event) => {
console.log('fired!')
}
document.getElementById('myElem').onmousedown = HandleEvent
1 Comment
If you want to pass an attribute
let HandleEvent = (event) => {
console.log('fired!')
}
document.getElementById('myElem').onmousedown = HandleEvent.bind(attribute)
Comments
What you did was assigning the result of HandleEvent() to the event, instead you should assign the function to it.
Correct statement:
document.getElementById('myElem').onmousedown = HandleEvent;
onmousedownexpects afunctionreference, but what you're passing is the returned value of the function (which isundefined) because you're invoking it. Trydocument.getElementById('myElem').onmousedown = HandleEventinstead.