Reputation: 8506
I have a pagination bar and it will switch to the next button if you click the "next" or "prev" arrow buttons.
I wrote some code to stay on the current "page" number if the next item in the list is ".next" or ".prev", but it is not working.
What am I missing?
$(document).ready(function() {
var pageItem = $(".pagination li").not(".prev,.next");
var prev = $(".pagination li.prev");
var next = $(".pagination li.next");
pageItem.click(function() {
$('li.active').removeClass("active");
$(this).addClass("active");
});
// stay on current button if next or prev button is ".next" or ".prev"
next.click(function() {
if($('li.active').next() != next) {
$('li.active').removeClass('active').next().addClass('active');
}
});
prev.click(function() {
if($('li.active').prev() != prev) {
$('li.active').removeClass('active').prev().addClass('active');
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav>
<ul class="pagination">
<li class="prev">
<a href="#"><span>«</span></a>
</li>
<li class="active"><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li class="next">
<a href="#"><span>»</span></a>
</li>
</ul>
</nav>
Upvotes: 2
Views: 150
Reputation: 5468
jQuery selectors return an Array object, objects cannot be deemed equal unless they are derived from each other.
i.e.
var a = []
var b = []
console.log(a==b); //would output false
If you changed you code to select the item in the array you would get the actual DOM node
$('li.active').next()[0] != next[0]
Upvotes: 2
Reputation: 4690
All you need to check the class name, Please check below updated code
$(document).ready(function() {
var pageItem = $(".pagination li").not(".prev,.next");
var prev = $(".pagination li.prev");
var next = $(".pagination li.next");
pageItem.click(function() {
$('li.active').removeClass("active");
$(this).addClass("active");
});
// stay on current button if next or prev button is ".next" or ".prev"
next.click(function() {
if($('li.active').next().attr('class') != 'next') {
$('li.active').removeClass('active').next().addClass('active');
}
});
prev.click(function() {
if($('li.active').prev().attr('class') != 'prev') {
$('li.active').removeClass('active').prev().addClass('active');
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav>
<ul class="pagination">
<li class="prev">
<a href="#"><span>«</span></a>
</li>
<li class="active"><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li class="next">
<a href="#"><span>»</span></a>
</li>
</ul>
</nav>
Upvotes: 1