When the page is loaded, the button is clicked automatically, but I don't want the function display() to be called until I click the button. How should I fix it?
<button id="button">Click</button>
window.onload = function () {
var button = document.getElementById("button");
button.onclick = display();
}
I tried
button.addEventListener("click", display());
but the same problem still occurred.
CodePudding user response:
When using ()
the function will be called, so use raw display
window.onload = function () { var button = document.getElementById("button"); button.onclick = display; }
CodePudding user response:
When you type display()
, what you're saying to Javascript is, "I'd like to call the display function now, please." So when you type
button.addEventListener("click", display());
you're similarly saying to Javascript, "I'd like to attach an event listener to the click event with the result of the display function, please." You want to be saying to Javascript, "I'd like you to attach this function display
to the click event, please. Only call it when the button is clicked." How do we do this in Javascript? Pass the function, but don't call it!
button.addEventListener("click", display);
CodePudding user response:
Try preventing the defaults
button.addEventListener("click",(e)=>{
e.preventDefaults();
})
You can have a further study on how the method works on the following link: https://www.w3schools.com/jsref/event_preventdefault.asp