I have a pagination. I need to style the current link in my pagination. For that I need to add a class "active" to the current link so that I can style it with css
Here is the javascript I have:
var itemsNumber = 6, $items, pages = 1, current = 1;
function makePages(){
$items = $(".filtered-div:visible");
pages = Math.ceil($items.length / itemsNumber);
$("#pages").empty();
for(var p=1;p<=pages;p++){
$("#pages").append($('<a href="#">'+p+'</a>'));
}
showPage(1);
}
function showPage(page){
$items.hide().slice((page - 1) * itemsNumber, page * itemsNumber).show();
current = page;
$("div.ctrl-nav a").show();
if(current == 1){
$("div.ctrl-nav a:first").hide();
}else if(current == pages){
$("div.ctrl-nav a:last").hide();
}
}
makePages();
$("div.ctrl-nav").on('click', 'a', function(){
var action = $(this).text();
if(action == 'Précédent'){
current--;
}else if(action == 'Suivant'){
current++;
}else if(+action > 0){
current = +action;
}
if(current <= 1){
current = 1;
}else if(current >= pages){
current = pages;
}
showPage(current);
});
And this is my HTML:
<div id="item-wrapper">
<div class="filtered-div" data-tag="['category-1']">item 1</div>
<div class="filtered-div" data-tag="['category-1']">item 2</div>
<div class="filtered-div" data-tag="['category-2']">item 8</div>
<div class="filtered-div" data-tag="['category-2']">item 9</div>
<div class="filtered-div" data-tag="['category-2']">item 10</div>
<div class="filtered-div" data-tag="['category-2']">item 11</div>
<div class="filtered-div" data-tag="['category-2']">item 12</div>
<div class="ctrl-nav">
<a href="#">Précédent</a><span id="pages"></span><a href="#">Suivant</a>
</div>
</div>
Here is a codepen: Codepen
Any suggestions? Thanks for your help
2
Answers
I’m not sure if I understand your question. You already solved the issue in your codepen example. The only thing left is adding CSS styling for the
active
class.Your paging buttons are added in a div with id
pages
, so you can reference the current page with:as your "page" (
current
) value is 1-based, but.eq
is 0-based, it needs to be-1
.Taking the more-complete code from the codepen and adding
active
to the current page link gives: