Reputation: 1144
I need to find the next and previous image starting from the img with the 'active' class within a div. The problem is, the search for the previous and next image always return a length of 0, so nothing happens.
<style>
.container #left img{
display:hidden;
}
.container #left img.active{
display:block;
}
</style>
<div class="container">
<div id="left">
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.jpg" />
<img src="4.jpg" />
<img src="5.jpg" />
</div>
</div>
<div class="arrow-left"></div>
<div class="arrow-right"></div>
<script>
$('.container #left img:first-child').addClass('active');
$(document).off('click', '.arrow-left').on('click', '.arrow-left', function() {
var prev = $('.container #left img.active').closest('div').prev().find('img');
if (prev.length == 0) {
prev = $('.container #left img:last');
}
$('.container #left img').removeClass('active');
prev.addClass('active');
});
</script>
Upvotes: 0
Views: 2044
Reputation: 9813
As what I commented, you can use .next and .prev to find the immediately following/preceding sibling. And as id
should be unique, the class .container
is not necessary here.
So you can rewrite the selector to :
$('#left img.active').prev('img')
To select the previous image.
And you can re-use the logic of left and right by using .is('arrow-left')
to decide whether the user clicked left or right.
$('.container #left img:first-child').addClass('active');
$(document).off('click', '.arrow-left, .arrow-right').on('click', '.arrow-left, .arrow-right', function() {
var next;
var circler;
if ($(this).is('.arrow-left')) {
next = 'prev';
circler = ':last';
} else { // or if there would be more arrows, use : else if ($(this).is('.arrow-right'))
next = 'next';
circler = ':first';
}
// Use bracket notation to dynamically decide which function to call.
var nextTarget = $('#left img.active')[next]('img');
if (nextTarget.length == 0) {
nextTarget = $('#left img' + circler);
}
$('#left img').removeClass('active');
nextTarget.addClass('active');
});
#left img {
display: inline-block;
width: 20px;
height: 20px;
}
#left img.active {
background-color: cyan;
}
.arrow-left, .arrow-right {
display: inline-block;
width: 50px;
background-color: lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="left">
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.jpg" />
<img src="4.jpg" />
<img src="5.jpg" />
</div>
</div>
<div class="arrow-left">Left</div>
<div class="arrow-right">Right</div>
Upvotes: 2