Vinícius Barcelos
Vinícius Barcelos

Reputation: 401

Get the previous element

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

Answers (3)

Shomz
Shomz

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

Shaunak D
Shaunak D

Reputation: 20646

Working Demo

  • You need to separate both the click handlers. The click of previous was inside the handler of net before.
  • Also, you need to handle the event where there is no previous element. For 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

Pete_Gore
Pete_Gore

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

Related Questions