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?
-
1Did you wrap that in $(document).ready() ?Praveen– Praveen2013-01-10 20:10:53 +00:00Commented Jan 10, 2013 at 20:10
-
Good question. I have tried it with and without that, and both ways the result is the same.Bluefire– Bluefire2013-01-10 20:11:34 +00:00Commented Jan 10, 2013 at 20:11
-
@Praveen what code? All I have is an element with the id "someelement" and the code that you can see above.Bluefire– Bluefire2013-01-10 20:13:36 +00:00Commented Jan 10, 2013 at 20:13
-
Duplicate stackoverflow.com/questions/2204647/…daniatic– daniatic2013-01-10 20:23:07 +00:00Commented Jan 10, 2013 at 20:23
2 Answers
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.
Try this:
$(document).ready(function() {
$("#someelement").click(function(){alert("click")});
});
Here is a working Fiddle