Reputation: 1
I'm totally new to jquery. I want to be able to set the header background image randomly. I don't want it to change each time the page is refreshed. Rather, I'd just like to set it once per session. I'm assuming I need to use a session cookie for this, but can't get it to work.
The following is what I have thatt works fine on a per-refresh basis. I just want to stop it changing on each refresh.
$(document).ready(function () {
var randomImages = ['image1', 'image2', 'image3', 'image4', 'image5'];
var rndNum = Math.floor(Math.random() * randomImages.length);
var imageFile = $('#imgpathname').val() + randomImages[rndNum] + ".jpg";
$("div#header").css({ background: "url(" + imageFile + ") no-repeat" });
});
Thanks very much for any help.
Upvotes: 0
Views: 1363
Reputation: 273
jQuery.cookie.js will likely be able to help you here:
https://github.com/carhartl/jquery-cookie/
From the project page, creating a session cookie is as easy as:
$.cookie('the_cookie', 'the_value');
You can then read this cookie back on each page load.
$.cookie('the_cookie'); // => "the_value"
I hope that helps. As suggested above, HTML5 local storage can be used, but a session cookie is more widely supported.
Upvotes: 1
Reputation: 6839
hi why dont you store your imageID in html5 storage objects such as sessionStorage/localStorage, visit Html5 Storage Doc to get more details. using this you can store intermediate values temporaryly/permanently locally and then access your values for storing values for a session
sessionStorage.getItem('label')
sessionStorage.setItem('value', 'label')
or store values permanently using
localStorage.getItem('label')
localStorage.setItem('value', 'label')
So you can store (temporarily) form data between multiple pages using html5 storage objects which u can even retain after reload..
Now in your case you can store image ID in sessionstorage and use it whenever page is refreshed so that same image is loaded per session.
Upvotes: 1