Sam
Sam

Reputation: 111

Hide show button when last item shows

I want show eavry more_item on click of more and hide the more when last item shows

    <ul class="home_projects">
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li class="more_item">4</li>
      <li class="more_item">5</li>
      <li class="more_item">6</li>
    </ul>

    <a href="#" class="more">more</a>

Using Jquery

$(".more_item").hide();
        $(".more").click(function() {
        $(".more_item:hidden:first").slideDown("slow");
         });
  if ($('.more_item:hidden:last').is(':visible')){
   $(".more").hide();
        }

Upvotes: 0

Views: 218

Answers (4)

Luca Rainone
Luca Rainone

Reputation: 16458

First, you should put the last if in onclick handle.

Second you should not check if the last is hidden, because it's visible during animation. So.

$(".more_item").hide();
$(".more").click(function() {
    $(".more_item:hidden:first").slideDown("slow");
    if ($('.more_item:last').is(':visible')){
        $(".more").hide();
    }
});

Upvotes: 0

skz
skz

Reputation: 165

You can do it this way:

$('.more').on('click', function() {
  if ($('.more_item:hidden').length > 0) {
    $('.more_item:hidden:first').slideDown('slow');
  } else {
    $(this).hide();   
  }
});

jsFiddle here.

Upvotes: 0

Jarvan
Jarvan

Reputation: 1210

When the code running to if ($('.more_item:hidden:last').is(':visible')),the animation may not finish yet,so you should write the hide code in the callback of slideDown, it will run when the animation is finished.

Example:

$(".more_item").hide();
        $(".more").click(function() {
        $(".more_item:hidden:first").slideDown("slow",function(){
         $(".more").hide();
    });
});

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try this way -

$(".more_item").hide();
$(".more").click(function() {
    $(".more_item:hidden:first").slideDown("slow",function(){
      if ($('.more_item:hidden').length === 0){
        $(".more").hide();
      }
    });
});

Demo ------> http://jsfiddle.net/cjHp7/

Upvotes: 2

Related Questions