Reputation: 14099
I have some html on my page, and in my head I have $("#someelement").click(alert("click"));
. Whether #someelement exists or not, when I load the page for some reason the alert goes off. However, it doesn't execute when I have $("#someelement").click(function(){alert("click")});
. Why is that?
Upvotes: 0
Views: 69
Reputation: 95030
alert("foo")
will always alert foo immediately, it does not return a function that you can pass as an event handler. You need to pass a function into the jQuery event binding method instead.
$("#someelement").click(function(){
alert("click");
});
Additionally, if this code is in the <head></head>
, it needs to be wrapped in $(document).ready()
.
$(document).ready(function(){
$("#someelement").click(function(){
alert("click");
});
});
alert
is a method defined on the window
object, such as, window.alert
. It expects one parameter that is a string, and it must be a member of the window object. placing ("string")
after alert
, such as alert("string")
will execute that function, resulting in the popup window with "string"
. The same thing happens when you place alert("string")
as a parameter to a function, a popup window happens when said code runs.
Upvotes: 2
Reputation: 5155
Try this:
$(document).ready(function() {
$("#someelement").click(function(){alert("click")});
});
Here is a working Fiddle
Upvotes: 0