0
votes

I'm using a custom JavaScript pagination in our project but now I need to know how to hide the next or prev button using JavaScript or jQuery.

  1. If I click to last number then hide the next button else show it.
  2. If I click to 1 number then hide the perv button else show it.

My code is given below:

$(document).ready(function(){
      
    $("#pageNavPosition > span").on("click", function(){
       var thisBtn = $(this);
        $("#pageNavPosition > span").removeClass('active');
        thisBtn.addClass('active');
         var btnLg = $("#pageNavPosition > span").length;
    });
    
});
#pageNavPosition >span{
    
    border:solid 1px red;
    padding:3px 5px;
    float:left;
    margin:2px;
    cursor:pointer;
}
.active{
    
    background:#ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="pageNavPosition" style="display: block;">
    <span>  Prev </span>  
    <span>1</span>  
    <span>2</span>
    <span >3</span>  
    <span> Next </span></div>
2

2 Answers

2
votes

try this:

$(document).ready(function(){
      var n = $("#pageNavPosition > span").size();
    $("#pageNavPosition > span").on("click", function(){
       var thisBtn = $(this);
        $("#pageNavPosition > span").removeClass('active');
        thisBtn.addClass('active');
        if(thisBtn.index() == (n-2))
        {
            $("#last").hide();
            $("#first").show();
        }
        else if(thisBtn.index() == 1)
        {
            $("#first").hide();
            $("#last").show();
        }
        else
        {
             $("#first").show();
             $("#last").show();
        }
        
    });
    
});
#pageNavPosition >span{
    
    border:solid 1px red;
    padding:3px 5px;
    float:left;
    margin:2px;
    cursor:pointer;
}
.active{
    
    background:#ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="pageNavPosition" style="display: block;">
    <span  id="first">  Prev </span>  
    <span>1</span>  
    <span>2</span>
    <span >3</span>  
    <span id="last"> Next </span></div>
1
votes

add page-number class to all numbered elements like

<span class="page-number">1</span>

then using jQuery

$("#pageNavPosition > span.page-number").first().on("click", function(){
  $(this).prev().hide();
});

$("#pageNavPosition > span.page-number").last().on("click", function(){
  $(this).next().hide();
});

PS : you need to handle show separately.