Venelin
Venelin

Reputation: 3308

jQuery - click function not working after remove() is used

Sample of HTML:

<div class="row" id="ThumbnailHolder">
    <div class="col-md-12">
        <img src="http://images.sportsdirect.com/images/products/16503236_pit.jpg" class="Thumbnails" bigimagelink="http://images.sportsdirect.com/images/products/16503236_l.jpg">
        <img src="http://images.sportsdirect.com/images/products/16503236_piat_a1.jpg" class="Thumbnails" bigimagelink="http://images.sportsdirect.com/images/products/16503236_l_a1.jpg">
    </div>
</div>

Here is my code:

$(document).ready(function() {
    $('.Thumbnails').each(function() {
        $(this).click(function() {
                  var BigImageLink = $( this ).attr( "bigimagelink" );
                  $('#ImgBigLink').attr('href', BigImageLink);
                  $('#productImgDefault').attr('src', BigImageLink);
        });

    });     
});

This function is working great. When i click an element with class Thumbnails everything goes how i need. The Problem comes when i execute the following part of code:

$.ajax({
    url: 'CheckColorPrice.php',
    type: 'POST',
    data: {
        url: '<?php echo $url;?>',
        ColorId: ColorNumber,
        ProductUrl: '<?PHP echo $ProductUrlWithoutCode;?>'
    },
    dataType: 'json',
    success: function (data) {
            $( ".Thumbnails" ).remove();
            $.each(data.thumbnails, function(index, thumbnails) {                             
            $('#ThumbnailHolder div').append('<img src="http://images.sportsdirect.com/images/products/' + thumbnails + '" class="Thumbnails" bigimagelink="http://images.sportsdirect.com/images/products/' + thumbnails + '">');  
            }); 
    }
});

I am pretty sure the problem comes from $( ".Thumbnails" ).remove(); but i need it to remove all the images with class Thumbnails and then replace them with the new ones which are appended with the same structure and class. When this code is executed the CLICK function on Thumbnails is just not responding. There are no output errors ot what so ever. Why my click function is not working anymore ?

I am pretty sure you can help me with this.

Thanks in advance!

Upvotes: 1

Views: 273

Answers (1)

Satpal
Satpal

Reputation: 133403

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically.

General Syntax

$(staticParentElement).on('event','selector',callback_function)

Example

$('#ThumbnailHolder div').on('click', '.Thumbnails', function(){    
    var BigImageLink = $( this ).attr( "bigimagelink" );
    $('#ImgBigLink').attr('href', BigImageLink);
    $('#productImgDefault').attr('src', BigImageLink);
});

Upvotes: 2

Related Questions