I just wrote a few jQuery lines to have a simple slider on the page.
I do not need this slider, so I will disable the PREV/ buttons NEXTwhen we reach the beginning / end of the list. It works fine for NEXT, but I can’t understand why it doesn’t work for PREV(you can see that the button is not disabled, even if the first item is active).
Does anyone see what I missed?
$(function(){
function sliderUpdate(elements) {
$(elements).toggleClass('active');
var active = $('#slider li.active');
$('#slider .prev').toggleClass('disabled', active.is(':first-child'));
$('#slider .next').toggleClass('disabled', active.is(':last-child'));
}
$('#slider').on('click', '.previous:not(.disabled)', function(event) {
var toToggle = $('#slider li.active');
toToggle = toToggle.add(toToggle.prev('li'));
sliderUpdate(toToggle);
});
$('#slider').on('click', '.next:not(.disabled)', function(event) {
var toToggle = $('#slider li.active');
toToggle = toToggle.add(toToggle.next('li'));
sliderUpdate(toToggle);
});
sliderUpdate($('#slider li').first());
});
#slider li.active {
color: red;
}
#slider .disabled {
color: #ddd;
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="slider">
<a href="#" class="previous">PREVIOUS</a>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<a href="#" class="next">NEXT</a>
</div>
Run codeHide result
zessx source
share