Reputation: 105
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.
Upvotes: 4
Views: 150
Reputation: 353
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;
$('#prev').click(function() {
// Fade just the container - not each placeholder meaning the callback function is only called once, not four times
$('.container').animate({
opacity: 0
}, 1000, function() {
$('.container .divname:eq(0)').before($('.container .divname:eq(3)'));
// Fade back in just the container - not each placeholder
$('.container').animate({
opacity: 1
}, 1000);
});
return false;
});
Upvotes: 2
Reputation: 5967
other than friends suggested (Ids should really be unique) i saw misspell in your code.change "divnaname"
to "divname"
in the div tags.e.g: <div id="divnaname"> ... <div>
Edit:
check this demo demo
is this what you are trying to do?
Upvotes: 0