Anna Riekic
Anna Riekic

Reputation: 738

jquery show div when :last is shown

As the title says I'm trying to get a div to show when :last is shown, here is what I have so far

$(function() {
    $('#d').hide();
    var $images = $('#d1 > .c1 > a').clone(),
        $imgShow = 0;
    $('#d1 > .c1').html($('#d1 > .c1 > a:first'));
    $('#d1 > .c1 > a').click(function(e) {
        var $n = $('img', $images).eq(++$imgShow).attr('src');
        $(this).children().attr('src', $n);
        e.preventDefault();
    });
});

see jfiddle for demo

I tried with on :last click but that didn't seem to work (hence it being commented out in jfiddle) plus having it be shown when :last is in view is a better option anyway, how can this be achieved?

Upvotes: 1

Views: 63

Answers (1)

João Silva
João Silva

Reputation: 91299

last isn't working because you are manipulating the DOM with the html() call. A better approach would be to store the total image count, and then show the div when you have reached the last image (i.e., totalImages == imgShow):

var $images  = $('#d1 > .c1 > a').clone(),
    $imgShow = 0,
    totalImages = $images.length;

// ...

$('#d1 > .c1 > a').click(function(e) {
  var $n = $('img', $images).eq(++$imgShow).attr('src');
  $(this).children().attr('src', $n);
  e.preventDefault();

  if ($imgShow == totalImages) {
    $("#d").show();   
  }
});

Fiddle.

Upvotes: 2

Related Questions