Kern Elliott
Kern Elliott

Reputation: 1659

How keep content on a page even when I leave then return to the page with Jquery

Currently I have a page created with Jquery Mobile and the content on the page is formed based on the URL id such as this http://domainname/page?id=2. The way I get the content is a ajax request when the page event beforepageshow is fired, using this jquery statement $(document).on( "pagebeforeshow", "#player", function( e ). This works fine however I want to know how i can retain this content even when I move away from the page.

For example if I go back i should go to a list however if a press button it should take me back to player page and shows all the content that I got from the ajax request on the page and the proper URL. How can this be done?

Upvotes: 2

Views: 332

Answers (1)

Gajotres
Gajotres

Reputation: 57309

There are several way this can be achieved. You will need to store your data or to move it during the page transitions. Here are some possible solutions:

Data/Parameters storing between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$("#index").live('pagebeforeshow', function () {
    var parameters = $(this).data("url").split("?")[1];;
    parameter = parameters.replace("parameter=","");  
    alert(parameter);
});

This will only work on multi html page format.

Solution 2:

Or you can create a persistent javascript object for a storage purpose. As long ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
    firstname : '',
    lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$('#index').live('pagebeforeshow', function (e, data) {
    alert(data.prevPage.attr('id'));
});   

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
    localStorage.firstname="Dragan";
    localStorage.lastname="Gaic";            
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

Everything mentioned here and much more can be found in my other ARTICLE, or HERE. Just search for the chapter called: Data/Parameters storing between page transitions

Upvotes: 1

Related Questions