Src Src - 5 months ago 21
Javascript Question

Javascript automatic function execution

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:


  1. Why?

  2. How to make it work properly?


Answer
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)