Src Src - 1 year ago 107
Javascript Question

Javascript automatic function execution

If i'm writing event in this way, action executes when it should:

document.getElementById('myElem').onmousedown = (e) => {

But if i'm writing same stuff in other way, action executes when page is loaded, once:

let HandleEvent = (event) => {
document.getElementById('myElem').onmousedown = HandleEvent(event)

Ofcourse it is just example,
function will have much more complex logic.

My questions is:

  1. Why?

  2. How to make it work properly?

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download