0
addEventListener
I relate submit button so that it display a text "welcome" when clicked. As usual <button id="btn" onclick="display message()">display</button> display message(){ var a = document.getElementById("btn"); a.alert("Welcome"); But this time I use: a.addEventListener("click", (display message()); The problem arise here. When I use a.addEventListener("click", (display message()); Why It doesn't wait until the button btn pushed or pressed then invoke displayMessage()? Instead, it automatically invoke function displayMessage() without waiting for the keypressed or button btn pushed? Thank you for your explanation class....
7 Réponses
+ 3
Brother try to attached your code or effort while u ask this type of question not in the description section instead separately as an attachment, that our mentor Tibor Santa SIR mentioned. At least we can understand u do an effort for your answer.
Here is your answer. When u use a.addEventListener("click", displayMessage());, u are actually calling the displayMessage function immediately instead of waiting for the click event to trigger it. To fix this issue & make sure the displayMessage function runs only when the button is clicked, u should pass a reference to the function without the parentheses when adding the event listener. By passing displayMessage without the parentheses in the addEventListener method, u are telling the browser to only execute that function when the button is clicked. Here it is⤵️
https://sololearn.com/compiler-playground/WH2Kl2jViGUl/?ref=app
+ 2
Why don't you link your code?
You cannot have white space inside a function name. So the code in your description is syntactically incorrect.
alert is a method of the window, and it does not need the button to work.
alert("your message")
+ 2
Your code:
a.addEventListener('click', display());
Fixed:
a.addEventListener('click', display);
Notice the absence of the parentheses. Doing this will not execute the function, but bind the function itself to the click event.
+ 1
Ok
0
Tibor Santa , нттp⁴⁰⁶ I enclose the code.
0
Oh, I understand. Thank you very much