Jump to content
Stelian

Save changes after reloading the page with local storage

Recommended Posts

Hello, I am trying to make website with inclusive design for my homework and I have three functions that are changing the text size, text style and site color theme, but I can not save the changes after I reload the page.  This is my code for changing the text size:

localStorage.setItem('z''1');
function size() {
  if (localStorage.getItem('z')=="1"){
    txt = document.getElementById("a").style.fontSize = "25px";
    localStorage.removeItem("z");
    localStorage.setItem('z''2');
    }
    else if (localStorage.getItem('z')=="2") {
      txt = document.getElementById("a").style.fontSize = "30px";
      localStorage.removeItem("z");
      localStorage.setItem('z''3');
  }
  else {
    txt = document.getElementById("a").style.fontSize = "20px";
    localStorage.removeItem("z");
    localStorage.setItem('z''1');
  }
}
The code in my html is this:
<body onload="size()">
<button  type="button" onclick="size();">Change Text Size</button>
<div  id='a'>Some text</div>
</body>
 
I believe I can make the other two function save their changes If I see how to make this one.
Thank you !

Share this post


Link to post
Share on other sites

The first line always reset it on every reload, you only need that to happen when it has not already been set and is empty. Also the JavaScript code needs to below any element it references as the page is rendered from top to bottom, the jS code is executed before the elements it is referencing even exist producing undefined error.

You are overthinking this, all you need do is set

localStorage.fontsize=1;

or

localstorage.fontsize=2; and so on...

On click event it should increment a variable on each click then reset if greater than 3 the use if conditions

	n++;
	if(n > 3){
	n=1;
	}
	localStorage.fontsize=n;
	if (localStorage.fontsize==1){
	document.getElementById("a").style.fontSize = "20px";
	}
	// and so on...
	

On load you should see if fontsize exists else set to defalut

	if (localStorage.fontsize) {
if (localStorage.fontsize==1){
	document.getElementById("a").style.fontSize = "20px";
} 
	// and so on...
	 
	else {
  localstorage.fontsize=1;
}
	


 

Edited by dsonesuk
  • Thanks 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...