Reputation: 169
I try to add interactions to my slider How to add a class to previous div
The first part of the script is responsible for changing clases. If you put the current class to another div, the div before it will get .prv and the div after current will get .nxt
But now, when I add click function to a button (next) to remove current class, clases .nxt and .prv still remain, they should disappear. Please check the fiddle: https://fiddle.jshell.net/df9ef0hf/12/
<div class="next">next</div>
<div class="previous">prev</div>
<div class="main-slider">
<div class="slide current"></div>
<div class="slide "></div>
<div class="slide " ></div>
<div class="slide "></div>
<div class="slide "></div>
</div>
as
$(".main-slider").ready(function(){
$(".current").prev().addClass("prv");
$(".current").next().addClass("nxt");
if( ! $(".current + div").length ) $('.slide').first().addClass("nxt"); // current is last
if( ! $(".current").prev().length ) $('.slide').last().addClass("prv") // current is firs
});
$('.next').click(function() {
$('.current').removeClass('current');
});
UPDATE / Working fiddle https://fiddle.jshell.net/df9ef0hf/15/
Upvotes: 0
Views: 54
Reputation: 896
You were not re assigning the current class, thus the script does not know what the current object is. Try this:
var update = function() {
$(".current").prev().addClass("prv");
$(".current").next().addClass("nxt");
if( ! $(".current + div").length ) $('.slide').first().addClass("nxt"); // current is last
if( ! $(".current").prev().length ) $('.slide').last().addClass("prv") // current is firs
};
$(".main-slider").ready(function(){
update();
});
$('.next').click(function() {
$('.current').removeClass('current');
$( ".nxt" ).addClass( "current" ).removeClass( "nxt" );
update();
});
Upvotes: 1