I am making a website with the option to change font-size. Every time when you refresh the page though, the font-size you selected returns to the original font-size. The code below shows the html and JavaScript code for how this function works:
let buttons = document.querySelector('.buttons');
let btn = buttons.querySelectorAll('.btn');
for (var i = 0; i <btn.length; i++){
btn[i].addEventListener('click', function(){
let current = document.getElementsByClassName('clicked');
current[0].className = current[0].className.replace("clicked", "");
this.className += " clicked";
})
}
:root {
--secondary-color: #4978ff;
}
.sec .buttons {
width: 100%;
display: flex;
justify-content: flex-end;
align-items: flex-end;
margin-bottom: 20px;
}
.sec .buttons .btn {
padding: 0 10px;
display: inline-flex;
background: #ddd;
color: var(--primary-color);
margin-left: 10px;
cursor: pointer;
}
.sec .buttons .btn.clicked {
background: var(--secondary-color);
}
.sec .buttons .btn:nth-child(2) {
font-size: 1.5em;
}
.sec .buttons .btn:nth-child(3) {
font-size: 2em;
}
<section class="sec">
<div class="content">
<div class="buttons">
<span class="btn clicked" onclick="document.getElementById('text').style.fontSize = '1em'">A</span>
<span class="btn" onclick="document.getElementById('text').style.fontSize = '1.25em'">A</span>
<span class="btn" onclick="document.getElementById('text').style.fontSize = '1.75em'">A</span>
</div>
<div class="text" id="text">
<h3>i'm an h3</h3>
<p>i'm a paragraph</p>
</div>
</div>
</section>
I was wondering if it was possible to store the chosen font-size in the localStorage so that it stays the same after you refresh the page?
You can do it by creating a function that changes the
fontSizeand add it on theLocalStorageevery time a person clicks on it.After that you can use the
window.onload()to always check, when the page loads, if there is anyfontSizeon theLocalStorageand set it if there is.Example:
HTML
JavaScript
Upgraded Version
HTML
JavaScript