jquery bbq - detect when user clicks back button

1k Views Asked by At

I've successfully implemented the jQuery BBQ plugin to build a quick prototype, however I am having one small issue related to my particular setup:

  • One of the pages, "#catalogue", includes a grid of items that are generated randomly using a function, "randomItems()", triggered on hashchange (when coming from another page).
  • The user then clicks on any of these items in the grid to view the #detailspage.
  • Upon clicking on the browser Back button, I'd like the user to view the #catalogue page (which works fine) BUT prevent the page from generating a new set of random items onload (so keep whatever items were last shown).

Is there a way to know that the user has hit the back button, so in that case I don't trigger the "randomItems()" function?

3

There are 3 best solutions below

4
vher2 On

You need to put the items from randomItems() in a cache:

// save your records here in the cache
var items = [];

$(window).on('hashchange', function(){
    var page = window.location.hash.replace(/^#/, '');

    // check first if items has already records in it and check if page is #catalogue
    // if not then call randomItems()
    if (page === 'catalogue' && items.length === 0) {
        items = randomItems();
    }

    // your code here follows
});
0
monkeyhouse On

use the browser's local storage to save the item. first create a javascript representation of the object. Then store it in the localStorage. Retrieve in on page load. Note that you will have to stringify the complex object to store it because the storage only accepts key value pairs

heres a general pattern

var foo;
window.onpageload = function(){
   if(localStorage["foo"] == '' | localStorage["foo"] == undefined){
     foo = getrandomItems(); //possibly an ajax call;
     localStorage["foo"] = JSON.stringify(foo);
   else{
     foo = JSON.parse(localStorage["foo"]);
   }
};

see http://diveintohtml5.info/storage.html and Storing Objects in HTML5 localStorage for details

0
user2562940 On

Believe bbq allows you to set and get url parameters, you can use these to determine if you need to randomise. When the user clicks link to catalog the url is something like:

http://yoururl.com/#catalog

So this is the "root" url for catalog and whenever the url is this you randomise Items, after randomising the items you add a param to the url so it becomes say:

http://yoururl.com/#catalog?r=1

This way when the user goes off and looks at an item and then clicks back historic url will contain the r=1 and as such you do not process the randomise function.

function randomiseItems()
{
  // we do not want to randomise
  if(urlParamIsSet("r")) return; 

  // set url param so gets stored in history (replacing current url)
  urlSetParam("r",1); 

  //-- do your code here
}

Instead of urlParamIsSet/urlSetParam use whatever function bbq provides for you to manipulate url.