baba-dev
baba-dev

Reputation: 2632

why jQuery prev doesn't work in this case?

I have group of section each has prev and next navigation buttons to navigate to the co-responding section.

<section id="sec1">
<img src="css/images/prev-btn.png" class="prev" />
<img src="css/images/next-btn.png" class="next" />
</section>
<div class="seperator"></div>
<section id="sec2">
    <img src="css/images/prev-btn.png" class="prev"/>
    <img src="css/images/next-btn.png" class="next" />
</section>
<div class="seperator"></div>
<section id="sec3">
<img src="css/images/prev-btn.png" class="prev"/>
<img src="css/images/next-btn.png" class="next" />
</section>

the next button is working just fine with the following code:

$('.next').click(function () {
    var next = $(this).parent().next();
    $.scrollTo(next, 1500, { easing: "easeInOutCirc" });

});

but the prev button does not navigate to the prev element.

i have tried:

This

$('.prev').click(function () {
    var prev= $(this).parent().prev();
    $.scrollTo(prev, 1500, { easing: "easeInOutCirc" });
});

and

$('.prev').click(function () {
    var prev= $(this).parent().prevAll().last();
    $.scrollTo(prev, 1500, { easing: "easeInOutCirc" });

});

and

$('.prev').click(function () {
    var prev= $(this).parent().prev('section');
    $.scrollTo(prev, 1500, { easing: "easeInOutCirc" });

});

what am i doing wrong?

Upvotes: 0

Views: 704

Answers (1)

Ilia G
Ilia G

Reputation: 10211

This should do it for you

var prev = $(this).parent().prevAll("section").attr("id");

Note that prevAll() appears to return elements ordered by distance from this, so the closest one will be first. And since attr() returns attribute for the first matching element, there is no need to call first() or last() on it. Magic simply happens.

Upvotes: 3

Related Questions