So I’m building a very simple carousel with 4 divs. It uses 2 jQuery functions to set a div to either first or last position. There is only alpha transitions as I don’t need movement.
For some reason, though I can access my divs with .eg(n) etc, but the first, last and other various numbers aren’t working in this function.
Code:
$('#prev').click(function() {
$('.container .divname').animate({opacity: 0}, 1000,function(){
$('.container .divname:first').before($('.container .divname:last'));
$('.container .divname').animate({opacity: 1}, 1000);
});
return false;
});
So that function isn’t working.
$('#prev').click(function() {
$('.container .divname').animate({opacity: 0}, 1000,function(){
$('.container .divname:eq(0)').before($('.container .divname:eq(3)'));
$('.container .divname').animate({opacity: 1}, 1000);
});
return false;
});
This also doesn’t work, but if I change the eq(3) to eq(2) it does, but obviously misses one of my divs. I can still access the eq(3) because I tested it, and made it’s background red.
$('.container .divname:eq(3)').css({'background-color' : '#ff0000'});
This works…
Can anyone please tell me why this maybe happening?
Html example is as below
<html>
<div class="container">
<div class="divname">
<p>some content</p>
</div>
<div class="divname">
<p>some content</p>
</div>
<div class="divname">
<p>some content</p>
</div>
<div class="divname">
<p>some content</p>
</div>
</div>
</html>
EDIT:
I have changed all the id to class now for the w3c kids in the audience. Issue still resides.
The root of your problem is that you have put your .before() function to shift the divs in a callback function attached to your four divs – thus it is called four times meaning everything is shifted four times bringing you back to square one …and becuase it’s such a simple little loop, it’s fast and it appears nothing has happened.
Solution – attach the animate function to just the container;
http://jsfiddle.net/cywjs/1/