Carl Papworth
Carl Papworth

Reputation: 1322

use variable change on second click

When clicking the .button I want to hide 4 posts, then show the next 4 posts, and clicking on .button a SECOND time should hide those 4 posts now visible (i.e post 5-8) and show the next 4 (post 9-12) and so on.

My code looks something like this:

  var i = 0;
  function fadeOutFour(){
      $('.post').eq(i++).fadeOut(1000, function(){
        $('.post').eq(i++).fadeIn(1000);
        $('.post').eq(i++).fadeIn(1500);
        $('.post').eq(i++).fadeIn(2000);
        $('.post').eq(i++).fadeIn(2500);
      });
      $('.post').eq(i++).fadeOut(750);
      $('.post').eq(i++).fadeOut(500);
      $('.post').eq(i++).fadeOut(250);  
  }

  $('.button').click(function(){
        fadeOutFour(function(){
            i += 4;
        });
  });

Now I can't get the NEW variable after click to work. So first of, what am I doing wrong? And also if there is a smoother and smarter way to do this, please let me know :) Cheers!

Upvotes: 0

Views: 144

Answers (2)

Muhammad Umer
Muhammad Umer

Reputation: 18097

The easier and compact way to do this is this

Take a look

http://jsfiddle.net/techsin/cfBeu/4/

  • No preloading of next items till previous ones are gone.
  • ability to load extra items even if they are not exactly n/4.
  • Less code.
  • Smoother.

Code Below:

var n=v=4, time= 500, $p= $('.post'), t =true;


$('.button').click(function(){
    if(t){
        t=false; if(n<$p.length+1) so();
    }});

st();
function st() {$p.slice(n-v,n-0).fadeIn(time,function(){t=true;});}
function so() {$p.slice(n-v,n-0).fadeOut(time,function() {st();}); n+=v;}

Upvotes: 3

cssyphus
cssyphus

Reputation: 40038

Is this the sort of thing you are looking for?

Working jsFiddle here

var i = 0;
$('.post').eq(i++).fadeIn(1000);
$('.post').eq(i++).fadeIn(1500);
$('.post').eq(i++).fadeIn(2000);
$('.post').eq(i++).fadeIn(2500);

function fadeOutFour() {
    firstHide(i);
    thenShow(i);
    i += 4;
}

function firstHide(i) {
    h = i - 4;
    $('.post').eq(h++).fadeOut(1000);
    $('.post').eq(h++).fadeOut(750);
    $('.post').eq(h++).fadeOut(500);
    $('.post').eq(h++).fadeOut(250);
}

function thenShow(i) {
    $('.post').eq(i++).fadeIn(1000);
    $('.post').eq(i++).fadeIn(1500);
    $('.post').eq(i++).fadeIn(2000);
    $('.post').eq(i++).fadeIn(2500);
}

$('.button').click(function () {
    fadeOutFour(function () {
        i += 4;
    });
});

Upvotes: 1

Related Questions