1

I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

 $(".A").click( function () {

    // do something

 });

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

4 Answers 4

3

You need to use $.live

$(".A").live('click', function () {

   // do something

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

Comments

0

Have a look at the live() jquery method to automatically wire up events to new elements. Or, as you create the new button, attach the new click event.

var newbutton = $('<input type="button" value="click me"/>');
somediv.append(newbutton);
newbutton.click(yourhandler);

Comments

0

Your event handler fires at page load, before your button exists.

Either reset the event handler after you create the button, or use .live for late-binding:

$(".A").live('click', function () {
   // do something
});

Now the handler will apply to .A even created in the future.

Comments

-1

you have to use the live-function of jquery! In difference to the click-function, it watches for dom manipulations. as you can imagine its slightly slower than the .click().

$('.clickme').live('click', function() {
  // Live handler called.
});

Felix

3 Comments

You mean, the function that you didn't use in your code example?!?
Yes this is the bind method You should have copied this example from the docs $('.clickme').live('click', function() { // Live handler called. });
It's "slightly slower"? Slightly slower at what? They do different jobs. If you compare how fast this method is at doing X and how fast the other method is at doing X, the result is "infinite" because the other method cannot do X.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.