aryan singh
aryan singh

Reputation: 827

Javascript, Jquery ,DOM

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");
});

Upvotes: 1

Views: 53

Answers (2)

LcSalazar
LcSalazar

Reputation: 16839

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");
    })
);

Upvotes: 0

DarkAjax
DarkAjax

Reputation: 16223

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

Upvotes: 3

Related Questions