The first thing i noticed is that your setting your id variable on document ready which means it will always be "div01" and never change.
jQuery(document).ready(function() {
(function ($) {
var a = $('.active').attr('id'); // a will always = div01
Also the if blocks are only hit once when the document is ready so it will never check what id it is after the first time.
You are also assigning two different click events to each button, one in the if block and one below the if block. This can cause it to skip a slide because it is firing two different click events that both change what the active slide is.
What you need to do is assign your id inside of the click event so it changes every time you click one of the buttons. You would also need to do your if blocks inside of your click events too.
// next button click event
$('#next').on('click',function() {
var a = $('.active').attr('id');
if (a == "div04"){
$('.active').removeClass('active');
$("#div01").addClass('active');
}
else{
$('.active').removeClass('active').next().addClass('active');
}
});
Here's the final code.
$(function(){
$('#next').on('click',function() {
var a = $('.active').attr('id');
if (a == "div04"){
$('.active').removeClass('active');
$("#div01").addClass('active');
}
else{
$('.active').removeClass('active').next().addClass('active');
}
});
$('#preview').on('click',function() {
var a = $('.active').attr('id');
if (a == "div01"){
$('.active').removeClass('active');
$("#div04").addClass('active');
}
else{
$('.active').removeClass('active').prev().addClass('active');
}
});
});
Here's a working jsfiddle example
Below is another way you could do it without needing to check the id's.
$(function(){
var slides = $(".slide"); // gets all elements with the slide class
$("#next").click(function(){
var $active = $(".active");
$active.removeClass("active");
if($active.next(".slide").length > 0) // Check if next element exists
$active.next(".slide").addClass("active");
else
$(slides[0]).addClass("active"); // Make first slide active
});
$("#prev").click(function(){
var $active = $(".active");
$active.removeClass("active");
if($active.prev(".slide").length > 0) // check if next element exists
$active.prev(".slide").addClass("active");
else
$(slides[slides.length -1]).addClass("active"); // Make last slide active
});
});
Here's the working jsfiddle example