0

After appending a button on Html document the jQuery event associated with it not working ?

For example:

$("#mydiv").append('<a href="#" id="mybutton">X</a>');//this is button appending

$("#mybutton").click(function(){
    alert("hello");
});
4
  • you gotta wait a ms or 2, or use $("#mydiv").on("click","#mybutton", ... ) Commented Sep 9, 2014 at 21:28
  • Is this your actual code (i.e. do these lines run sequentially)? In that case, do you have more than one element matching #mybutton in your document? Commented Sep 9, 2014 at 21:30
  • 4
    works for me: jsfiddle.net/xwrpf5gq... Commented Sep 9, 2014 at 21:32
  • It works. If it doesn't, it's probably a duplicate of stackoverflow.com/q/12829963/218196 Commented Sep 9, 2014 at 21:36

2 Answers 2

3

Assuming you call the .click() method on #mybutton before it is actually appended to #mydiv, you need to use .on() as the button doesn't exist when you attach the event handler:

$('#mydiv').on('click','#mybutton',function(){
    alert('hello');
});

Should work...

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

3 Comments

If the code is as he posted, he adds the element before attaching the handler, so he doesn't need to do this.
@Barmar Indeed, I assumed that wasn't the case, as otherwise the original code would work...
Either way, if that's the reason then the question should be closed as duplicate of e.g. stackoverflow.com/q/12829963/218196. We really don't need more of these.
0

Why don't you set the click inside the append?

This way you wouldn't need to concern about the element being added or not to the document's flow, since you'd be setting the event callback on the actual DOM element variable:

$("#mydiv").append(
    $('<a href="#" id="mybutton">X</a>').click(function() {
        alert("hello");
    })
);

Comments

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.