Reputation: 141
I want to know why when i execute this in html
<!DOCTYPE html>
<html>
<p class="click">
click here
</p>
<script>
p=document.querySelector(".click");
p.addEventListener("onclick",alert("click sucess"))
</script>
</html>
the alert will appear straight away fire after I open the browser, but not on click . and how do I make it fire when I click it.
Upvotes: 1
Views: 319
Reputation: 65806
That's because you are passing executable code as the callback, rather than a function reference. As soon as the JavaScript runtime gets to that line, it simply executes the code you've place there.
.addEventListener()
requires a reference to a function to call when the specified event occurs. So, you need to wrap your executable code in a function (as I'm showing below) or simply reference a function by name that is already defined.
Also, the event is click
, not onclick
(that's an event property).
<p class="click">click here</p>
<script>
p = document.querySelector(".click");
p.addEventListener("click", function(){ alert("click sucess") } );
// Or, reference a pre-existing function:
function secondHandler(){
alert("Even more success!");
}
p.addEventListener("click", secondHandler);
</script>
Upvotes: 1
Reputation: 943517
The second argument to addEventListener
needs to be a function.
The expression alert("click sucess")
will immediately call the alert
function (passing it an argument) and evaluate as the return value of that function.
It is equivalent to:
var a_value = alert("click sucess");
p.addEventListener("onclick", a_value);
You need to create a new function that calls alert with the desired arguments.
Additionally, you need to get the name of the event correct. It is click, not onclick.
var a_value = alert.bind(window, "click sucess");
p.addEventListener("click", a_value);
Upvotes: 1