RW Hammond
RW Hammond

Reputation: 113

HTML5 & jQuery LocalStorage

This is my first go at localStorage and its not going. I have the jQuery code below to increase the page font size if an element is selected. Problem is when you go to a new page, it reverts back. I've tried some different variations but I am stuck. Any help is appreciated.

$textSize1.click(function() {
  $( "body" ).css("font-size", "10px");
  localStorage.setItem("$textSize1", $textSize1);
});
$textSize2.click(function() {
  $( "body" ).css("font-size", "20px");
  localStorage.setItem("$textSize2", $textSize2);
});
$textSize3.click(function() {
  $( "body" ).css("font-size", "30px");
  localStorage.setItem("$textSize3", $textSize3);
});

localStorage.getItem("$textSize1");
$textSize1.click(function() {
  $( "body" ).css("font-size", "10px");
  localStorage.setItem("$textSize1", $textSize1);
});
$textSize2.click(function() {
  $( "body" ).css("font-size", "20px");
  localStorage.setItem("$textSize2", $textSize2);
});
$textSize3.click(function() {
  $( "body" ).css("font-size", "30px");
  localStorage.setItem("$textSize3", $textSize3);
});

localStorage.getItem("$textSize1");

Upvotes: 1

Views: 287

Answers (1)

Maxime Rouiller
Maxime Rouiller

Reputation: 13699

What is happening is that you are storing the value and fixing the style in the current page but you are not doing the same operation when the page load again.

This is normally done in the onReady written in jQuery like this : $(document).ready(function() {...});

Just reading the value won't do much. You need to use it!

I think I've captured what you were trying to do and reimplemented your code:

var defaultFontSize = "10px";

$(document).ready(function(){
    var fontSize = localStorage.getItem("fontSize") || defaultFontSize;
    $( "body" ).css("font-size", fontSize);
})

$fontSize1.click(function() {
  $("body").css("font-size", "10px");
  localStorage.setItem("fontSize", "10px");
});
$fontSize2.click(function() {
  $("body").css("font-size", "20px");
  localStorage.setItem("fontSize", "20px");
});
$fontSize3.click(function() {
  $("body").css("font-size", "30px");
  localStorage.setItem("fontSize", "30px");
});

Upvotes: 3

Related Questions