Question

How would I create a cookie that would store the randomly added body class for one browser session or for one day. My intention would be to randomly give every user a body background image and then store that image so that it won't change every pagereload or when they go to page 2.

Site http://www.midnightlisteners.com/

i am using this jQuery plugIn: https://github.com/carhartl/jquery-cookie

but it does not work somehow

My jQuery code:

the code that I use:

if($.cookie('userBackground') === null) {
    var classes = ['body-bg1','body-bg2', 'body-bg3', 'body-bg4'];
    var randomnumber = Math.floor(Math.random()*classes.length);
    var chosenClass = classes[randomnumber];
    $('body').addClass(chosenClass );
    $.cookie('userBackground', chosenClass, { expires: 7, path: '/' });
} else {
   //todo verify cookie value is valid
   $('body').addClass($.cookie('userBackground'));
}

Errors i am getting:

Uncaught ReferenceError: require is not defined
Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'cookie'  

Are there other ways to do this? php? pure javascript?

Was it helpful?

Solution

UPDATE:

If you want to make it only last the length of the session then just use the session instead:

<?php 
if(!isset($_SESSION['bgclass'])) {
   // lets make our cookie!
   $classes = array('body-bg1','body-bg2', 'body-bg3', 'body-bg4');

   $classIndex = array_rand($classes);

   $_SESSION['bgclass'] = $classes[$classIndex];

}       

$bgclass = $_SESSION['bgclass'];
?>

This way after the session times out or the browser is closed the user will get a new bgclass value.


If you already have php running i would do it that way. Much better to handle this server side if you can. Its also a bit simpler:

<?php 
if(!isset($_COOKIE['bgclass'])) {
   // lets make our cookie!
   $classes = array('body-bg1','body-bg2', 'body-bg3', 'body-bg4');
   $expire = time()+(60*60*24); // expire 1 day form now
   $classIndex = array_rand($classes);

   $bgclass = $classes[$classIndex]; // had $class here as opposed to $classes

   setcookie('bgclass', $bgclass, $expire);

} else {
  $bgclass = $_COOKIE['bgclass'];
}
?>
<html>
  <head></head>
  <body class="<?php echo $bgclass ?>">
    ...
  </body>
</html>

The key thing to remeber is that a cookie is essentially a response header so you have to do this before headers have been sent (ie. anything from php is output to the browser).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top