Reputation: 401
I'm trying to select my previous .item
I have this:
<div id="um" class="item">um</div>
<div id="dois" class="item">dois</div>
<div id="tres" class="item active">tres</div>
<div id="quatro" class="item">quatro</div>
<div id="cinco" class="item">cinco</div>
<button id="prev>previous</button>
and i'm trying with this:
$("#prev").click(function(){
$(".active").addClass("after").removeClass("active");
$(".after").prev(".item").addClass("active");
$(".after").removeClass("after");
});
i'm failing to retrieve the previous .item
Can anyone help me?
Upvotes: 0
Views: 64
Reputation: 37711
Works fine, you need to close quote on the button id attribute.
<button id="prev">previous</button>
See here: http://jsfiddle.net/4YLjg/
UPDATE
According to the link from the comment, your prev
click listener is defined within your next
click listener, so each time you click the next button, it generates a new prev
listener which results in prev
getting triggered one additional time for every time you clicked the next button...
See the working version here: http://codepen.io/anon/pen/cGrvq
Upvotes: 3
Reputation: 20646
um
press previous.Next :
$("#next").click(function () {
// SETANDO A CONTAGEM DE ITENS
var len = $(".active.item").next(".item").length;
// ADICIONANDO O PRÓXIMO ITEM
$(".active").addClass("before").removeClass("active");
$(".before").next(".item").addClass("active");
$(".before").removeClass("before");
// SE FOR O ÚLTIMO ITEM, RETORNE AO PRIMEIRO
if (len <= 0) {
$(".active").addClass("before").removeClass("active");
$(".item").first().addClass("active");
$(".before").removeClass("before");
}
});
Previous :
$("#prev").click(function () {
var len = $(".active.item").prev(".item").length;
$(".active").addClass("after").removeClass("active");
$(".after").prev(".item").addClass("active");
$(".after").removeClass("active").removeClass('after');
console.log(len);
if (len <= 0) {
$(".active").addClass("after").removeClass("active");
$(".item").last().addClass("active");
//$(".after").removeClass("before");
}
});
Upvotes: 0
Reputation: 634
You don't have to overload JS using another class. Have you tried this :
$("#prev").click(function(){
var prev = $(".active").prev();
$(".active").removeClass("active");
prev.addClass("active");
});
There's a good example like what you wanna do on the jQuery official prev() page : http://api.jquery.com/prev/
Upvotes: 0