Grigori Grigori - 5 months ago 21
JSON Question

Create previous/next html page navigation

I have a series of pages named "page-1" "page-2" "page-3" ..."page-99". Is there a way to make a navigation so that whenever I click the "next" button it goes to the next page, and if I click "previous" it will go to the previous page depending on what the current page number is. I was wondering if there is a javascript solution to this since I have never used PHP.



<a href="#" id="next">next</a> <!--it will go to page-3-->
<a href="#" id="prev">previous</a> <!--it will go to page-1-->




Answer

This should get you started (starting with your original code).

$('a[class^=page]').click(function(e){
   e.preventDefault();
   var num = this.className.split('-')[1]; //2
   var nav = $(this).attr('data-nav');
   if (nav == 'next'){
         num = parseInt(num)+1;
         //window.location.href = "page-"+num+'.html';
   }else{
         num--;
         //window.location.href = "page-"+num+'.html';
   }
  alert('Navigating to: [ page-' +num+ '.html ]');
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<a href="#" class="page-2" data-nav="next">next</a> <!--it will go to page-3-->
<a href="#" class="page-2" data-nav="prev">previous</a> <!--it will go to page-1-->


Of course, this would be easier:

$('a[class^=page]').click(function(e){
   e.preventDefault();
   var num = this.className.split('-')[1]; //2
  
   //window.location.href = "page-"+num+'.html'; //The "real" code
  alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<a href="#" class="page-1" >next</a> <!--it will go to page-3-->
<a href="#" class="page-3" >previous</a> <!--it will go to page-1-->

And this would be easiest (using the file name):

//className *starts with* nav-
$('[class^=nav-]').click(function(e){
   e.preventDefault();
   var fileName = location.pathname.split("/").slice(-1);
   var fileName = 'http://page-2.html'; //FOR DEMO ONLY
      //alert(fileName); //should respond page2.html
   var num = fileName.split('-')[1]; //2
   var nav = this.className.split('-')[1]; //next
   if (nav == 'next'){
         num = parseInt(num)+1;
         //window.location.href = "page-"+num+'.html';
   }else{
         num = parseInt(num)-1;
         //window.location.href = "page-"+num+'.html';
   }

alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only

});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<a href="#" class="nav-next" >next</a> <!--it will go to page-3-->
<a href="#" class="nav-prev" >previous</a> <!--it will go to page-1-->