I have the following code
document
.getElementById("myButton")
.addEventListener("click", myFunction(event));
function myFunction(event) {
alert("Click Event!");
event.preventDefault();
}
<btn id="myButton">Donate Now</span>
Html:
<btn id="myButton">Click Me</btn>
Javascript:
document
.getElementById("myButton")
.addEventListener("click", myFunction(event));
function myFunction(event) {
alert("Click Event!");
event.preventDefault();
}
The click event is being run on page load without console error and not on click event! .
I need to prevent a button' click event so I have to pass the event to do it.
And when I click on the button it doesn't run the event handler but gives console error of
Uncaught TypeError: Cannot read property 'preventDefault' of undefined
Despite me clearly passing the event. Surely if it runs this at page load without me wanting to it should be consistent and give the same error there?
I need to solve:
- Not fire the click event on page load
- The click event should not throw console error when clicked upon