I have developed a jQuery slider and I want to implement it in WordPress (it will be a Featured Posts slider).
This is my slider logic:
- If there are 1 or 3 posts, show them but hide the prev and next buttons.
- If there are more than 3 posts but less than or equal to 6, or more than 6, show navigation.
- If there are more than 6 posts, show navigation.
- After the animation is finished, hide the next button.
In my code, there are a lot of if
else
statement. Is there a better way to write my slider?
You can look at the Fiddle and try to delete div
s from container
(slider and its navigation will remain functional...)
jQuery:
$(document).ready(function () {
//If less than four divs Hide next button
if ($('.container div').length < 4) {
$('.next').hide();
}
//Also hide prev button
$('.prev').hide();
i = 0; //Click counter...
$('.next').click(function () {
//Prevent animation to mess up...
if ($('.container').is(':animated')) {
return false;
}
//Animate next click...
$('.container').animate({
marginLeft: '-=300'
}, 1000, function () {
i++; //Increase Var by One...
// Animation Callback If there are LESS than 6 divs
//hide next button
if ($('.container div').length <= 6) {
$('.next').hide();
}
// Else if there are more than 6 divs
//show next button
else if ($('.container div').length >= 6) {
$('.next').show();
}
//If first click exists show prev button
if (i == 1) {
$('.prev').show();
}
//If second click exists hide next button
else if (i == 2) {
$('.next').hide();
}
});
});
//on prev button click
$('.prev').click(function () {
//Prevent animation to mess up...
if ($('.container').is(':animated')) {
return false;
}
//Run animation...
$('.container').animate({
marginLeft: '+=300'
}, 1000, function () {
i--; //Decrase number of clicks
//If on prev click counter===0 hide prev button
//and show next button
if (i == 0) {
$('.prev').hide();
$('.next').show();
}
//Else if click===1 or click===0
//Show next button
else if (i == 1 || i == 0) {
$('.next').show();
}
});
});
});
HTML:
<div class="wrapper">
<div class="container">//If you delete those guys below //Slider and navigation will still work!!
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
<div class="seven"></div>
<div class="eight"></div>
<div class="nine"></div>
</div>
</div>
<!--/wrapper-->
<div class="nav_wrapper">
<div class="next">Next</div>
<div class="prev">Prev</div>
</div>
<!--/nav_wrapper-->