onclick Event Problem | Sololearn: Learn to code for FREE!


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

4/16/2018 2:40:08 PM


3 Answers

New Answer


remove the parentheses from the open function inside the addEventListener method


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.


Mohamed ELomari thank you! it works now!