WP Learner
WP Learner

Reputation: 830

show hide no of divs according to the current index jquery

I am working with jQuery index. Here I need to add and remove divs according to the current index.

What I looking for is I need to remove first four divs when my current index is greater than 7 and I need to show those removed first four divs again when my current index is less than four(4).

I used :lt(4) to hide first four divs. But I have no idea how to get it back to show.

Thanks in Advance

$(window).load(function() {

  $(document).keydown(function(e) {
	  if (e.keyCode == 37){

		 


	  }
	  else if (e.keyCode == 39){

		 


	  }
	  else if (e.keyCode == 40){

		  var cIndex = $('.foo.active').index();
      
          if(cIndex > 7) {

              $('.test').find('.foo:lt(4)').remove();

          }


	  }
	   else if (e.keyCode == 38){

		  var cIndex = $('.foo.active').index();
      
          if(cIndex < 4) {

              $('.test').find('.foo:lt(4)').add();

          }


	  }
  });
  
});  
.test {
  width: 420px;
  height: 200px;
  text-align: center;
}

.foo {
  width: 100px;
  height: 100px;
  line-height: 100px;
  display: inline-block;
  background: #ccc;
  margin-bottom: 4px;
}

.foo.active {
  background: #565656;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
    <div class="foo active">1</div>
    <div class="foo">2</div>
    <div class="foo">3</div>
    <div class="foo">4</div>
    <div class="foo">5</div>
    <div class="foo">6</div>
    <div class="foo">7</div>
    <div class="foo">8</div>
    <div class="foo">9</div>
    <div class="foo">10</div>
    <div class="foo">11</div>
    <div class="foo">12</div>
</div>

Upvotes: 3

Views: 289

Answers (1)

Farnabaz
Farnabaz

Reputation: 4066

You can add class hide to those element you gonna hide, then when you want show them back use that class and select them, just like this:

$('.foo:lt(4)').addClass('hide').fadeOut();
// when you show them back
$('.foo.hide').removeClass('hide').fadeIn();

Upvotes: 2

Related Questions