stormec
stormec

Reputation: 189

Remember state on refreshing - jQuery with cookie

I am trying to develop a script that would remember the state after page refresh.

Here is what I've done so far.

jQuery:

      $(window).ready(function() {
var voteId = $('.gallery-item a');
$(voteId).click(function() {
$(this).text('Thank you!');
$(this).css('background-color', 'green');
});
});

I have tried this, but didn't have luck with it:

jQuery:

var cookies = document.cookie.split(";");
    for(var i=0; i < cookies.length; i++) {
    var equals = cookies[i].indexOf("=");
    var name = equals > -1 ? cookies[i].substr(0, equals) : cookies[i];
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }

Upvotes: 2

Views: 1214

Answers (2)

Darren Willows
Darren Willows

Reputation: 2131

Set a Cookie

The parameters of the function below are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).

The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

Get a Cookie

Take the cookiename as parameter (cname).

Create a variable (name) with the text to search for (cname + "=").

Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')).

Loop through the ca array (i=0;i

If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length,c.length).

If the cookie is not found, return "".

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

Set and Get

setCookie("message", "Thank You", 365); 
setCookie("color", "#0F0", 365); 

var message=getCookie("message"); 
var color=getCookie("color");

This will set two cookies message and color with an exp of 1 Year. You could do it all in one with a JSON Array as well.

Upvotes: 3

Darren Willows
Darren Willows

Reputation: 2131

Take a look at JS Cookie as it does not require jQuery.

A simple, lightweight JavaScript API for handling cookies

Works in all browsers

Accepts any character

Heavily tested

No dependency

Unobtrusive JSON support

Supports AMD/CommonJS

RFC 6265 compliant

Enable custom decoding

Very good Wiki

~800 bytes gzipped!

https://github.com/js-cookie/js-cookie

Cookies.set('name', 'true', { expires: 7, path: '' });
Cookies.get('name'); // => 'true'
Cookies.remove('name', { path: '' }); 

Upvotes: 0

Related Questions