1

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");
});
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
aryan singh
  • 587
  • 2
  • 5
  • 16

2 Answers2

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...

DarkAjax
  • 15,175
  • 11
  • 52
  • 65
  • 4
    If the code is as he posted, he adds the element before attaching the handler, so he doesn't need to do this. – Barmar Sep 09 '14 at 21:32
  • @Barmar Indeed, I assumed that wasn't the case, as otherwise the original code would work... – DarkAjax Sep 09 '14 at 21:33
  • Either way, if that's the reason then the question should be closed as duplicate of e.g. http://stackoverflow.com/q/12829963/218196. We really don't need more of these. – Felix Kling Sep 09 '14 at 21:36
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");
    })
);
LcSalazar
  • 15,390
  • 3
  • 29
  • 62