Garrett
Garrett

Reputation: 438

Remove jQuery generated content with on()

I have some markup like this:

<div class="large-image">
    <img src="foo.jpg" class="original-size"> <--This persists
    <img src="foo-fullsize.jpg" class="zoomed"> <--injected by jQuery zoom plugin
    <img src="bar-fullsize.jpg" class="zoomed"> <--also injected
</div>

<div class="thumbnails">
    <a href="foo-fullsize.jpg" class="thumb"><img src="foo-thumb.jpg"></a>
    <a href="bar-fullsize.jpg" class="thumb"><img src="bar-thumb.jpg"></a>
</div>

I have some code like:

$(window).load(function() {
   $('a.thumb').click(function(){
      $('#main-image').zoom({url: this.href}); // jQuery zoom
   });
});

Every time I click a thumb link, the zoom plugin injects a new image into the <div class="large-image"> container. I would like to be able to remove all existing images with class zoomed before a new one is created. I know I need to use on() to accomplish this, but I can't seem to get it to work with the generated images.

Upvotes: 1

Views: 286

Answers (3)

Daryl Ginn
Daryl Ginn

Reputation: 1424

This should do it:

$(window).load(function() {
  $('a.thumb').on('click', function() {
    $('img.zoomed', this).remove(); 
  });
});

This will remove all .zoomed images relative to the thumbnail clicked. If you want to target every .zoomed image on the page, you'll want to drop the context:

$('img.zoomed').

Edit

I didn't realise it was generated content. Give this a whirl:

$(window).load(function() {
  $(document).on('click', 'a.thumb', function() {
    $('img.zoomed').remove(); 
  });
});

Upvotes: 3

Alexander
Alexander

Reputation: 23537

The selector $('img.zoomed') will match all the present <img> elements with a zoomed classname at the moment of execution indifferently of the way they were added.

$(window).load(function() {
   $('a.thumb').click(function(){
      $('img.zoomed').remove();
   });
});

Since the jQuery Zoom plugin creates extra elements next to the original images. You should try removing all <img> elements under div.large-image instead.

$(window).load(function() {
   $('a.thumb').click(function(){
      $('div.large-image img').remove();
   });
});

Upvotes: 2

Ramin Omrani
Ramin Omrani

Reputation: 3761

use jquery .remove() method:

$("img[class='zoomed']").remove();

or:

$("img.zoomed").remove();

Upvotes: 0

Related Questions