Search code examples
javascriptjquerylistpaginationlist.js

Getting a prev/next | first/last button to work with list.js


I am building a paginated index with search. I have the index paginated and working, however I want to add a prev/next and a first/last button because this has to be scalable.

List.JS does not seem to have one of these out of the box, so I tried to do it by appending/prepending the lis into the pagination div ul. This does work, except for after click they are removed.

Adding into pagination div

$('.pagination').prepend('<li class="btn-next"> 9 </li>');

$('.pagination').append('<li class="btn-prev"> 0 </li>');

Functions to run the buttons

$('.btn-next').on('click', function(){
    var list = $('.pagination').find('li');
    $.each(list, function(position, element){
        if($(element).is('.active')){
            $(list[position+1]).trigger('click');
        }
    })

})

$('.btn-prev').on('click', function(){
    var list = $('.pagination').find('li');
    $.each(list, function(position, element){
        if($(element).is('.active')){
            $(list[position-1]).trigger('click');
        }
    })

After this, Im not sure how I can even get them to stay appended since it seems to rewrite it on click every time. Has anyone else created these buttons using List.JS?

Here is my fiddle.


Solution

  • The problem is the plugin reloads the html every time you change the page, one option to avoid modify the plugin will be create an extra container and style your elements to be next other.

    The HTML will be like:

    <div class="nav">
      <ul class="pagination">
      </ul>
    </div>
    

    And then append your buttons:

    $('.nav').append('<div class="btn-next"> > </div><div class="btn-last"> >> </div>');
    $('.nav').prepend('<div class="btn-first"> << </div><div class="btn-prev"> < </div>');
    

    Updated Fiddle

    Still searching how to trigger first and last page


    For First and Last elements use the show() function:

    $('.btn-first').on('click', function(){
        monkeyList.show(1,1)
    })
    $('.btn-last').on('click', function(){
        monkeyList.show(monkeyList.size(),1)
    })
    

    Updated Fiddle 2