user3657273 user3657273 - 2 months ago 9
Javascript Question

Show items in first list pagination

I successfully can apply pagination to my data. But I don't know how to make the current active List - in this case, the first list Item shows up by default like doing tabs. Where the first list item shows up by default without needing someone to click on the button/link first in order to show the content of that current active list.

Below are my current codes I use:-

1) html code:

$(".pagination li").click(function () {
$(this).toggleClass('active').siblings().removeClass('active');
// hide all .block elements
$( ".block" ).hide();
// show .block with the same index as clicked li
$( ".block" ).eq( $( this ).index() ).show()
});


2) css code:

.pagination {
text-align: right;
margin: 0;
padding: 0;
margin: 0 0 10px;
}
.pagination li {
display: inline-block;
list-style: none;
padding: 10px 15px;
cursor: pointer;
}
.pagination li.active {
background: #003580;
color: white;
}

.block {
display:none;
}


3) html code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="pagination">
<li class="first active">1</li>
<li class="second">2</li>
<li class="third">3</li>
</ul>
<div class="block first">abc</div>
<div class="block second">123</div>
<div class="block third">!@#</div>


Can someone show me how to do this? Or maybe some other ways to do this?

Answer Source

Just add $( ".block" ).eq( $(".active").index() ).show(); into the script.

It will show the contents of the active tab

$( ".block" ).eq( $(".active").index() ).show();
$(".pagination li").click(function () {
    $(this).toggleClass('active').siblings().removeClass('active');
    // hide all .block elements
    $( ".block" ).hide();
    // show .block with the same index as clicked li
    $( ".block" ).eq( $( this ).index() ).show()
});
.pagination {
   text-align: right;
   margin: 0;
   padding: 0;
   margin: 0 0 10px;
}
.pagination li {
   display: inline-block;
   list-style: none;
   padding: 10px 15px;
   cursor: pointer;
}
.pagination li.active {
   background: #003580;
   color: white;
}

.block {
   display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="pagination">
    <li class="first">1</li>
    <li class="second">2</li>
    <li class="third active">3</li>
</ul>
<div class="block first">abc</div>
<div class="block second">123</div>
<div class="block third">!@#</div>