Sunday, October 19, 2014

How to keep same tab active in Twitter Bootstrap after page reload using localStorage

What is HTML Local Storage?

With local storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Local storage is per domain. All pages, from one domain, can store and access the same data data.

HTML local storage provides two objects for storing data on the client:
  • window.localStorage - stores data with no expiration date
  • code.sessionStorage - stores data for one session (data is lost when the tab is closed)


// for loading same tab after page reload using localstorage
    $(function() {
        //for bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line
        $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            //save the latest tab; use cookies if you like 'em better:
            localStorage.setItem('lastTab', $(e.target).attr('id'));
        });

        //go to the latest tab, if it exists:
        var lastTab = localStorage.getItem('lastTab');
        if (lastTab) {
            $('#'+lastTab).tab('show');
        }
    });

0 comments:

Post a Comment