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

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

4/16/2018 2:40:08 PM

fallOut015

3 Answers

New Answer

+1

remove the parentheses from the open function inside the addEventListener method

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

0

Mohamed ELomari thank you! it works now!