Frank78 Frank78 - 4 months ago 33
CSS Question

Store a changing jQuery variable to session or local storage

I currently have the following jQuery code working. Here's what it does: when I click a button, it will swap between classes. Each of those classes contains a background image. So, as I click this single button, it cycles through the background images. (edit: I just need to store whatever the current variable is, so when they swap pages, that variable is what's loaded).

$('.button').mousedown(function () {
$('#backgrounds').each(function(){
var classes = ['bg1','bg2','bg3','bg4'];
this.className = classes[($.inArray(this.className, classes)+1)%classes.length];
});
});


However, my website has multiple pages. So, what I need to do is store the current variable to the session storage or local storage, and then retrieve that variable on page load. That way as I jump from one page to another, the same class (and therefore background image) will be displayed. I don't need to (nor want to) use cookies -- I just need this to last the current session.

Additionally, if possible (though much less important than storing the variable), I'd also like this jQuery function to neatly fade when swapping from one background image to another. Right now it "snaps" from one image to the next as it swaps out the classes.

Thanks in advance -- any help greatly appreciated!

Answer

The selector #backgrounds should only match one element. So it is unnecessary to use each:

// Define classes & background element.
var classes = ['bg1','bg2','bg3','bg4'],
    $bg = document.getElementById('backgrounds');
// On first run:
$bg.className = sessionStorage.getItem('currentClass') || classes[0];
// On button click:
$('.button').mousedown(function () {
  // (1) Get current class of background element,
  // find its index in "classes" Array.
  var currentClassIndex = classes.indexOf($bg.className);
  // (2) Get new class from list.
  var nextClass = classes[(currentClassIndex + 1)%classes.length];
  // (3) Assign new class to background element.
  $bg.className = nextClass;
  // (4) Save new class in sessionStorage.
  sessionStorage.setItem('currentClass', nextClass);
});

In this demo I've used getElementById to select the #backgrounds DOM element, rather than selecting it using jQuery. This is because jQuery element representations don't actually have a className property, and the ordinary JavaScript API is simpler in this case.

Comments