HenryM HenryM - 3 months ago 13
jQuery Question

Hiding and revealing divs

I've a script which works fine when written like this:

var isPaused = false,
jQuery(function () {
var $els = $('div[id^=film]'),
i = 0,
len = $els.length;

$els.slice(1).hide();
setInterval(function () {
if (!isPaused) {
if (len > 1) {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len;
$els.eq(i).fadeIn();
});
}
}
}, 3500);
});


But I wanted to add a next and prev button so I rewrote like this, which I thought would work.

var isPaused = false,
$els = $('div[id^=film]'),
i = 0,
len = $els.length;

$els.slice(1).hide();
setInterval(Slide(1), 3500);

function Slide (x) {
if (!isPaused) {
if (len > 1) {
$els.eq(i).fadeOut(function () {
i = (i + x) % len;
if (i<0) {
i = len;
}
$els.eq(i).fadeIn();
});
}
}
}

$('#next').click(Slide(1));
$('#prev').click(Slide(-1));


But this code is just displaying all the divs when the page is loaded and then doesn't fade them in and out or allow the next and prev buttons to work. What am I doing wrong?

UPDATE
Perhaps I should ask this differently. Given the first block of code, how should I change it to enable Prev and Next buttons?

Answer

You want to do:

$('#next').click(function(){Slide(1);});
$('#prev').click(function(){Slide(-1);});

and

setInterval(function(){Slide(1);}, 3500);

instead, as with your current code, Slide(1) is already being computed, and the click function will just call the value returned from it (as it has no return in the function, this will not be defined)

By wrapping your calls to Slide in a function, this makes the clicks call that function, which in turn calls Slide

You also want to set your index to len - 1 if you go negative, rather than to len, as you're dealing with a zero indexed array:

if (i<0) {
    i = len - 1;
}