DaMaGeX
DaMaGeX

Reputation: 763

Cookies aren't always working

I have the following script:

function dsm_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;
}

function dsm_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 "";
}

jQuery(window).ready(function() {
  var fontsize = dsm_getCookie('class-fontsize');
  jQuery('body').prepend(fontsize); // Debug
  if (fontsize == 1) {
    jQuery('body').addClass('fontsize');
  }

  jQuery('.fontsize-small').click(function() {
    if (jQuery('body').hasClass('fontsize')) {
      jQuery('body').removeClass('fontsize');
    }
    dsm_setCookie('class-fontsize', 0, 30);
  });

  jQuery('.fontsize-large').click(function() {
    if (!jQuery('body').hasClass('fontsize')) {
      jQuery('body').addClass('fontsize');
    }
    dsm_setCookie('class-fontsize', 1, 30);
  });
});

Here I made an example on jsfiddle, which is working as it should. https://jsfiddle.net/9wdqp161/

Now, when I add the script to my wordpress, it sometimes works and sometimes doesn't. I've been trying to figure it for days, but I can't seem to find what is causing it.

Upvotes: 1

Views: 141

Answers (3)

Kaushik
Kaushik

Reputation: 2090

Alternative

localstorage

You can use local storage instead of cookie and very easy to use.

e.g.

localStorage.setItem('firstname', 'kaushik'); 
localStorage.getItem('firstname');
// output - kaushik

Upvotes: 1

rnevius
rnevius

Reputation: 27112

I'd try adding a path to your cookie definition in dsm_setCookie():

document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';

It's possible that the cookie is defaulting to the current path of the current document location...which may not be the root of your site.

Upvotes: 0

rishikesh tadaka
rishikesh tadaka

Reputation: 483

While using cookie, you need to take care of below points:

  • Do not exceed more than 50 cookies per domain.
  • Maximum limit of cookies is around 4k per domain. i.e. the size of all cookies should not exceed 4k. This means you can have 1 cookie of 4k or 2 cookies of 2k etc.

This may help you.

Upvotes: 0

Related Questions