Nikhil Srivastava
Nikhil Srivastava

Reputation: 239

a tag not Working when Dynamically Appended

i have appended a back button inside a div but it doesnt seems to be working. What could be the possible problem ?

 $(".blogposthr").append('<p style="font-size:10px; color:blue;margin-top:10px;padding-top:10px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Edit &nbsp;&nbsp;Delete&nbsp;&nbsp;<a href="#" id="back" style="text-decoration:none; color:blue;">Back</a></p><br>');

and i have added function calling it as

$("#back").click(function () {
    alert("Back Clicked");
    $(".b5").hide(800, "swing");
    $(".b").show(800, "swing");

});

Upvotes: 0

Views: 63

Answers (2)

Nishit Maheta
Nishit Maheta

Reputation: 6031

use below code . you also check Event delegation to attach event to dynamically created element. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

 $(document).ready(function(){

    $(document).on('click',"#back",function () {
       alert("Back Clicked");
       $(".b5").hide(800, "swing");
       $(".b").show(800, "swing");
    });

 });

Upvotes: 1

Frayt
Frayt

Reputation: 1223

Dynamically added items do not work with event binding, as event binding is performed once, when the page initially loads. instead use:

$('.blogposthr').on('click', '#back', function() {
    alert("Back Clicked");
    $(".b5").hide(800, "swing");
    $(".b").show(800, "swing");
});

Your selector (.blogposthr) needs to be a non-dynamically added object.

Upvotes: 1

Related Questions