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?
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.