Nicholas Maddren
Nicholas Maddren

Reputation: 155

Store Var Into Local Storage

Hi guys I'm aware that this question has been asked before however none of the answers seem to solve this issue.

I have this simple jQuery code:

var productName = jQuery('.product-name h1').html;

I'd like to store the productName variable into local storage so I can use the variable when the page is refreshed.

Can anybody show me how I can make this happen?

Thanks, Nick

Upvotes: 0

Views: 3711

Answers (2)

Grzegorz Gajda
Grzegorz Gajda

Reputation: 2474

To add new item to Web Storage API:

// First method
localStorage.setItem('VARIABLE_NAME', 'VARIABLE CONTENT');
// Second method
localStorage.VARIABLE_NAME = 'VARIABLE_CONTENT';

To retrieve value from Web Storage API:

localStorage.getItem('VARIABLE_NAME');
// or
localStorage.VARIABLE_NAME;

To store object, you need change Javascript Object to JSON notation:

localStorage.setItem('VARIABLE_NAME', JSON.stringify(JS_OBJECT));

Reference:

1. Using the Web Storage API

2. JSON.stringify()

After first comment, I think the proper way to do is:

Session.prototype.setDOMObject = function(name, object) {
    Session.setItem(name, JSON.stringify(object));
}

Session.prototype.getDOMObject = function(name) {
    var object = JSON.parse(Session.getItem(name));

    return $(object.selector);
}

This way, it stores a selector and it retrieves an object created using this selector. But it doesn't store the state of DOM element. If you want to save the state of DOM object (inside HTML), then you need to use .html() function.

Upvotes: 3

orourkedd
orourkedd

Reputation: 6421

localStorage.productName = jQuery('.product-name h1').html()

Upvotes: 1

Related Questions