Alan Dunning
Alan Dunning

Reputation: 1351

Selecting next div jquery

I am trying to select the .next() div to work within a carousel.

However, it seems to be returning all .children() rather than the .next()

HTML

<nav class="slider-navigation">
  <div class="left-arrow"></div>
  <div class="right-arrow"></div>
</nav>

<div class="slides">
  <div class="slide" id="slide1"></div>
  <div class="slide" id="slide2"></div>
  <div class="slide" id="slide3"></div>
  <div class="slide" id="slide4"></div>
</div>

JQUERY

$(".left-arrow").click(function () {

  var currentSlide = $(this).parent().siblings(".slides").children().next();

  // Do something with currentSlide.

});

When I console.log(currentSlide) in the browser it returns all 4 children of .slides.

The same happens for $(".right-arrow").click() I just did not want to add duplicate code

Any help?

Thanks

Upvotes: 0

Views: 466

Answers (2)

Eran.E
Eran.E

Reputation: 940

another option is to set the first element to the "current" class and use it to start the navigation between the slides.

*on prev control click, if there is no element before this one so nothing will happen and vice versa, so that's ok but if you want it to change direction after the last/first element got the "current" class so tell me and i will update the code...

Here it is:

HTML:

<nav class="slider-navigation">
  <div class="left-arrow">left</div>
  <div class="right-arrow">right</div>
</nav>

<div class="slides">
  <div class="slide current" id="slide1"></div>
  <div class="slide" id="slide2"></div>
  <div class="slide" id="slide3"></div>
  <div class="slide" id="slide4"></div>
</div>

Jquery:

$(document).ready(function(){
    $(".left-arrow").click(function(){
        $('.current').prev().addClass('current');
        $('.current:first').next().removeClass('current');
    });
    $(".right-arrow").click(function(){
        $('.current').next().addClass('current');
        $('.current:last').prev().removeClass('current');
    });
});

live example: http://jsfiddle.net/spvLpjct (i've put some CSS to help you understand it).

Upvotes: 1

Falk
Falk

Reputation: 26

If the current slide is visible and the rest are hidden you could use:

$(".left-arrow").click(function () {

  var currentSlide = $(".slides > .slide:visible").next();

  // Do something with currentSlide.

});

Upvotes: 0

Related Questions