0

The situation I have an index.html and in this file I have loaded content from subpages.
This my code in index.html

function getpage(page){
  var pageSrc = 'content/'+page+'.html';
  $('.content').load(pageSrc);
}

<a href="#" onClick="getpage('home')">Home</a>
<a href="#" onClick="getpage('about')">About</a>
<a href="#" onClick="getpage('contact')">Contact</a>

So,here, I want to create something like session or cookie using javascript/jquery method that can maintain the last page visited if users reloaded index.html page.The Important thing,the last page visited will be removed and back to normal index page when users cleared their browser cache or cookie.

smile
  • 35
  • 5

3 Answers3

1

You can use the jQuery Cookie plugin by Klaus Hartl to easily set & read browser cookies.

Once the plugin is loaded, you could add the following function to load the user's last page visited, or the index page by default:

$(document).ready(function(){
  var lastPage = ( $.cookie("lastPage") == null ) ? "index" : $.cookie("lastPage");
  getpage(lastPage);
});

Then modify your getpage function to keep track of each "page" view:

function getpage(page){
  var pageSrc = 'content/'+page+'.html';
  $('.content').load(pageSrc);
  $.cookie("lastPage", page);
}

This answer to similar question has some more examples, like how to set an expiration date on your cookie.

Community
  • 1
  • 1
dancriel
  • 86
  • 4
1

why do you need cookies for ? I think you might need something like a last click history

here is the code hope you get it :

<script>
   function page(){
   window.location.href = window.history.back(1);
}
</script>
<input type="button" value="loading" onclick="page()"/>
Ramin Taghizada
  • 125
  • 2
  • 9
1

The answer of Ramin Taghizada is better for me. There is another option: You can use localStorage if you want.

<a href="#" onClick="localStorage['prev'] = 'home'; getpage('home')">Home</a>
<a href="#" onClick="localStorage['prev'] = 'about'; getpage('about')">About</a>
<a href="#" onClick="localStorage['prev'] = 'contact'; getpage('contact')">Contact</a>

To see which the last page is the user clicked:

if(localStorage['prev'] != undefined)
{
  alert(localStorage['prev']);    
}
  • Thanks,I tested and working fine,is it compatible also using tab or android device? – smile Apr 08 '15 at 18:18
  • I have no idea, I'm sorry =( I have never tested but I guess it works on that, because I have used localStored in safari and Chrome as well – razielx4crazy Apr 08 '15 at 20:33