'How would I use localStorage to remember button click in PugJS?

This is what I have in my .pug file that I need the website to remember. If a user clicks the Large button then the website should remember that when the website is refreshed.

.scaling
        scalingButton(onclick='body.style.fontSize = "1.0em"')='Normal' 
        scalingButton(onclick='body.style.fontSize = "1.2em"')='Medium'
        scalingButton(onclick='body.style.fontSize = "1.5em"')='Large'

and here is what I have in the .css file for these buttons:

.scaling{
    text-align: end;
    position: fixed;
    margin: 150px;
    margin-right: 0%;
    margin-bottom: 5%;
    bottom: 0px;
    right :20%;
}

scalingButton{ 
    background-color: white;
    padding: 5px 10px;
    
    margin-top: 600px;
    font-weight: bold;
    border-radius: 3px;
    border: 2px solid black;
    filter: drop-shadow(2px 2px 2px black);
    transition: 0.3s;
  }
  
  scalingButton:hover{
    background-color: grey;
    cursor: pointer;
  }


Solution 1:[1]

You need to write a function that stores value in localStorage and when page is loaded (DOMContentLoaded ) you need to check localStorage, if localStorage has a font-size then you can apply it to the body.

script:

function changeFontSize(size) {
    let fontSize = size + "em"
    body.style.fontSize = fontSize;
    localStorage.setItem('font-size', fontSize);
} 

document.addEventListener("DOMContentLoaded", function(event) {
    let fontSize = localStorage.getItem('font-size');

    if(fontSize) {
         body.style.fontSize = fontSize;
    }
});

template

.scaling
    scalingButton(onclick="changeFontSize('1.0em')")='Normal' 
    scalingButton(onclick="changeFontSize('1.2em')")='Medium'
    scalingButton(onclick="changeFontSize('1.5em')")='Large'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Iftikhor