0

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?

4
  • 1
    Did you wrap that in $(document).ready() ? Commented Jan 10, 2013 at 20:10
  • Good question. I have tried it with and without that, and both ways the result is the same. Commented 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. Commented Jan 10, 2013 at 20:13
  • Duplicate stackoverflow.com/questions/2204647/… Commented Jan 10, 2013 at 20:23

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Just out of interest, how come that is so?
because alert("Foo") does not return a function. $.fn.click() requires a function to be passed as it's first parameter. It's just how JavaScript works.
0

Try this:

$(document).ready(function() {
  $("#someelement").click(function(){alert("click")});
});

Here is a working Fiddle

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.