Click event is not firing after DOM changes in jQuery

usef_ksa picture usef_ksa · Oct 6, 2011 · Viewed 9.2k times · Source

I am trying to code ADD & DELETE button in HTML page to delete or add images code in the page. The DELETE button will delete the first image before the button. The ADD button will insert a new image to HTML page and the delete button to the image.

The code works fine: it deletes the image when DELETE button is clicked and it inserts the image when ADD button is clicked. The problem is: the delete button that inserted after ADD button is clicked is not working. So if you click on ADD button and then click on DELETE button the image will not hide; the click event is not firing.

Here is the code:

<html>
    <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>  
    <script type="text/javascript">

        $(document).ready(function(){
            $('.img-post input').after('<button type="button" >Delete</button>');

            $(".img-post button").click(function() {
                    $(this).prev().prev().remove();
                    $(this).prev().remove();
                    $(this).remove();
            });

            $(".add-img button").click(function() {
                    $('<img  src="image3.jpg" /><input type="hidden" name="allimages[]" value="image3.jpg" /><button type="button" >Delete</button><br />').appendTo('.img-post');
            });

        });


        </script>   
    </head>
    <body>
            <div class="img-post">
                <img  src="image1.jpg" /><input type="hidden" name="allimages[]" value="image1.jpg" /><br />
                <img  src="image2.jpg" /><input type="hidden" name="allimages[]" value="image2.jpg" /><br />
            </div>

            <div class="add-img">
                <button type="button" >Add image</button>
            </div>

    </body>
</html>

Answer

RoccoC5 picture RoccoC5 · Oct 6, 2011

Bind the event handler to the button's click event using live() instead of click():

$(".img-post button").live('click', function() {
    $(this).prev().prev().remove();
    $(this).prev().remove();
    $(this).remove();
});

This will ensure that all buttons which match your selector which are added after the initial DOM load will also fire the same function.

http://api.jquery.com/live/