sessionStorage

by martyk

HTML

<script src="https://raw.github.com/AlexChittock/JQuery-Session-Plugin/master/jquery.session.js"></script>
<div class="test"></div>

CSS

body {
    padding: 20px;
}
.test {
    width:20px;
    height:20px;
    float:left;
    background-color:rgb(255,0,0);
    padding: 5px;
    font-size:10px;
}

JavaScript

jQuery(function($){
    $.domain = {
        _domain: null,
        _init: function()
        {
            this._domain = document.location.origin;
        },
        get: function(key)
        {
            return window.localStorage.getItem(key);
        },
        set: function(key, value)
        {
            try {
                window.localStorage.setItem(key, value);
            } catch (e) {
                console.log("Local Storage not supported!");
            }
            return this;
        },
        remove: function(key)
        {
            try {
                window.localStorage.removeItem(key);
            } catch (e) {};
            return this;
        },
    };

    $.domain._init();

    var randomWidth,
        randomHeight;
    if (!(randomWidth= $.session.get("randomWidth"))) {    // assignment
        randomWidth = Math.random() * 300;
        $.session.set("randomWidth", randomWidth, true);
        console.log("just assigned and stored in sessionStorage: randomWidth: " + randomWidth);
    } else {
        console.log("from sessionStorage: randomWidth: " + randomWidth);
    }
    if (!(randomHeight= $.domain.get("randomHeight"))) {    // assignment
        randomHeight = Math.random() * 300;
        $.domain.set("randomHeight", randomHeight, true);
        console.log("just assigned and stored in localStorage: randomHeight: " + randomHeight);
    } else {
        console.log("from localStorage: randomHeight: " + randomHeight);
    }
    $(".test")
        .css({width: randomWidth, height: randomHeight})
        .text("width: "+ randomWidth)
    ;

});