TDave00 TDave00 - 1 year ago 91
jQuery Question

Jquery animate works in console, but not in script

I've been beating my head against this all day. I'm writing this little slider/image rotating script and I cannot get it to change these elements. I can animate the images from the console with

$('.slide:nth-child(1)').animate({display: 'block'});
, but nothing from the script.


<div id="main">
<div class="wrapper">
<div class="slider">
<div class="slide">
<img src="/_site/images/interior-decor.jpg" />
<div class="slide">
<img src="/_site/images/Showhome-Living-Room.jpg" />
<div class="slide">
<img src="/_site/images/SL-Master-bedroom-1.jpg" />


var sl = {} || [];
sl.imgs = $('.slide');
sl.cnt = 1;
sl.wait = 6000;
sl.num = sl.imgs.length; //count length of .slide divs
//hide all but first image
$('.slide:nth-child(n + 2)').css('display', 'none');
sl.func = function() {
var prev = sl.cnt; //even tried sl.cnt.toString()
var next = sl.cnt;
if (sl.cnt > (sl.num)) {
sl.cnt = 1;
$('.slide:nth-child(' + next + ')').animate({display: 'block'});
$('.slide:nth-child(' + prev + ')').animate({display: 'none'});
console.log('Previous: '+prev+' Next: '+next);
window.setInterval(function() {
}, sl.wait);

The script consoles out
Previous: 1 Next: 2
and so forth every six seconds, but nothing changes.

Answer Source

You cannot animate display property. You can animate opacity or max-height instead:

$('.slide:nth-child(' + next + ')').animate({opacity: 1})
$('.slide:nth-child(' + prev + ')').animate({opacity: 0});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download