0

onclick Event Problem

Why does the open() function run when the window loads? I think it has to do with the event listener--what can I do so that this does not happen? And is there a better alternative than adding an event listener, keeping in mind that I want to write all events in the JS, and refrain from using a onclick="open()" in the HTML. window.onload = function() { var b = document.getElementsByClassName("write")[0]; b.addEventListener("click",open()); function open() { alert(); } } https://cod

16th Apr 2018, 2:40 PM
fallOut015
fallOut015 - avatar
3 Antworten
+ 1
remove the parentheses from the open function inside the addEventListener method
16th Apr 2018, 2:53 PM
MO ELomari
MO ELomari - avatar
+ 6
It will just display an empty prompt after the web page was loaded in the browser as there's no string parameter in the alert. I guess there's no better way to do it instead of inlining the event in DOM as you've suggested, unless you want to work with event-driven JS framework like Angular or React.
16th Apr 2018, 2:48 PM
Zephyr Koo
Zephyr Koo - avatar
0
Mohamed ELomari thank you! it works now!
16th Apr 2018, 2:54 PM
fallOut015
fallOut015 - avatar