Adjust the size of the text and save it in a cookie for later use

I am in need of a script that can dynamically increase and decrease the font size on a website while retaining the user's chosen setting even after they return to the site. I believe utilizing cookies is the way to achieve this functionality. Despite finding an example script online, I encountered issues when implementing it as clicking on A+ (increaseFont) did not produce any results. The script can be found below:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js'></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>

<div>
    <span class="increaseFont">A+</span>
    <span class="decreaseFont">A-</span>
    <span class="resetFont">Aa</span>
</div>

<script>
var fontResize = {
    textresize : function(){
        var $cookie_name = "eip-FontSize";
        var originalFontSize = $("html").css("font-size");
 
        $.cookie($cookie_name, originalFontSize, { expires: 7, path: '/' });
 
        // if exists load saved value, otherwise store it
        if($.cookie($cookie_name)) {
            var $getSize = $.cookie($cookie_name);
            $("html").css({fontSize : $getSize + ($getSize.indexOf("px")!=-1 ? "" : "px")}); // IE fix for double "pxpx" error
        } else {
            $.cookie($cookie_name, originalFontSize);
        }
 
        // reset font size
        $(".resetFont").bind("click", function() {
            $("html").css("font-size", originalFontSize);
            $.cookie($cookie_name, originalFontSize);
        });
 
        // function to increase font size
        $(".increaseFont").bind("click", function() {
            var currentFontSize = $("html").css("font-size");
            var currentFontSizeNum = parseFloat(currentFontSize, 10);
            var newFontSize = currentFontSizeNum*1.05;
            
            if (newFontSize > 11) {
                $("html").css("font-size", newFontSize);
                $.cookie($cookie_name, newFontSize);
            }
            return false;
        });
 
        // function to decrease font size
        $(".decreaseFont").bind("click", function() {
            var currentFontSize = $("html").css("font-size");
            var currentFontSizeNum = parseFloat(currentFontSize, 10);
            var newFontSize = currentFontSizeNum*0.95;
            if (newFontSize > 11) {
                $("html").css("font-size", newFontSize);
                $.cookie($cookie_name, newFontSize);
            }
            return false;
        });
    }
}
 
$(document).ready(function(){
    fontResize.textresize();
})
</script>

*I stumbled upon another working example, however, it lacks the cookie feature which means the values reset to default on page reload: https://jsfiddle.net/pairdocs/yq8Le0gn/4/

Answer №1

  • One option is to utilize the localStorage() method for storing a value.
  • Adjust the CSS of the body to have a font-size of 16px.
  • Define font sizes for other elements using relative units such as em or rem.
  • Modify the font size specifically for the body element using JavaScript and observe the adjustment in other elements.

Incorporating +/- Buttons:

const EL_body = document.querySelector("body");
const ELS_fontSize = document.querySelectorAll(".fontSize");
localStorage.fontSize = localStorage.fontSize || 16;

function changeSize() {
  EL_body.style.fontSize = `${localStorage.fontSize}px`;
}

ELS_fontSize.forEach(el => el.addEventListener("click", function() {
  localStorage.fontSize = parseInt(localStorage.fontSize) + parseInt(el.value);
  changeSize();
}));

changeSize();
<button class="fontSize" type="button" value="-2">A-</button>
<button class="fontSize" type="button" value="2">A+</button>

<h1>Lorem ipsum...</h1>
<p>Lorem ipsum...</p>

Utilizing Radio Buttons:

const EL_body = document.querySelector("body");
const ELS_fontSize = document.querySelectorAll("[name='fontSize']");
localStorage.fontSize = localStorage.fontSize || 16;

function changeSize() {
  ELS_fontSize.forEach(el => el.checked = el.value === localStorage.fontSize);
  EL_body.style.fontSize = `${localStorage.fontSize}px`;
}

ELS_fontSize.forEach(el => el.addEventListener("change", function() {
  localStorage.fontSize = el.value;
  changeSize();
}));

changeSize();
[name="fontSize"]+span {
  display: inline-block;
  padding: 5px 10px;
  border: 1px solid currentColor;
}

[name="fontSize"]:checked+span {
  color: #0bf;
}
<label><input type="radio" name="fontSize" value="14" hidden><span>A-</span></label>
<label><input type="radio" name="fontSize" value="16" hidden checked><span>A</span></label>
<label><input type="radio" name="fontSize" value="18" hidden><span>A+</span></label>

<h1>Lorem ipsum...</h1>
<p>Lorem ipsum...</p>

Using a Select Box:

const EL_body = document.querySelector("body");
const EL_fontSize = document.querySelector("#fontSize");
localStorage.fontSize = localStorage.fontSize || 16;

function changeSize() {
  EL_fontSize.value = localStorage.fontSize;
  EL_body.style.fontSize = `${localStorage.fontSize}px`;
}

EL_fontSize.addEventListener("change", function() {
  localStorage.fontSize = this.value;
  changeSize();
});

changeSize(); 
<select id="fontSize">
  <option value="14">Small</option>
  <option value="16">Normal</option>
  <option value="18">Big</option>
</select>
<h1>Lorem ipsum...</h1>
<p>Lorem ipsum...</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Minimize the space between flex items

I'm currently working with a <div> container styled as flex using the following CSS properties: .icon-container { padding: 3px; padding-top: 15px; padding-bottom: 15px; display: flex; flex-direction: column; align-content ...

Discovering the droppable container that a draggable element is positioned within

Currently, I am utilizing jQuery UI for drag and drop functionality. My main goal is to determine which droppable area a draggable element has been placed in. Can anyone offer assistance? Below is the code I am working with: $(".draggable").draggable({ ...

Positioning an immovable element beneath a fixed element that can vary in height

I am working on a webpage that features a fixed menu at the top-left corner, followed by the main content. My goal is to ensure that the content appears below the menu, but since I do not know the exact height of the menu in advance (as it can vary based o ...

EaselJS: Enhancing Performance and Aesthetics with Over 200 Vector Shapes

When comparing EaselJS performance with Canvas native methods, I noticed a significant difference: 2.2 s vs 0.01 s (despite EaselJS mapping canvas native methods). I created a canvas application that draws a tree*. For animating the growth of the tree, us ...

Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler. const middleware = (req: Request, res: Response, nex ...

There is an abundance of brief PHP documents

After conducting some initial research, I have realized that I need more information on the topic at hand. My interactive website relies on ajax calls to retrieve data from the server. Authenticated users engage with this data through various actions, whic ...

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...

Performing asynchronous operations in React with axios using loops

On the backend, I have a socket set up to handle continuous requests from the server. Now, my goal is to send requests to the backend API continuously until a stop button is clicked. Using a loop for this task is considered bad practice as it never checks ...

Looking for the quickest hash and salt method for IP addresses in Node.JS?

Currently, there are many stipulations regarding the tracking of user data such as unique visits and returning users. An issue arises in certain regions where IP addresses are considered sensitive personal information. To continue identifying unique user ...

Obtaining Spotify API access token using JavaScript code on the front end

I've developed a web application that enables users to generate a list of songs by artists related to a selected artist. The goal is to link the user's Spotify account and create a playlist based on this generated song list, which requires obtain ...

The users in my system are definitely present, however, I am getting an error that

Whenever I attempt to retrieve all the post.user.name, an error is displayed stating Cannot read properties of undefined (reading 'name') I simply want to display all the users in my node Even though user is not null, when I write post.user, i ...

Forking a Node.js child process to assign it CPU affinity

Looking to utilize the child_process.fork function in Node.js for spawning a new process. This example is also applicable with the spawn function. To optimize CPU usage and make sure that these child processes are distributed evenly across all cores of th ...

I am interested in finding a method to preview how my website will appear and function on a mobile device while using a desktop browser

Similar Question: Emulators and Simulators for Testing Mobile Browser Compatibility? I'm interested in seeing how my website appears and functions when accessed on mobile devices like an iPhone, iPad, Android, etc. The challenge is that I do not ...

Is horizontal spacing automatically added to <img> elements in Bootstrap? And if it is, how can this default setting be changed or overridden?

I'm currently working on the design for a homepage where I want to showcase the same image repeated 4 times in a row, creating a decorative banner effect. Each image is set to occupy 25% of the screen width, which should theoretically fit perfectly si ...

Experiencing inconsistencies with CSS on certain devices?

When faced with a research issue, I usually turn to Google for answers. However, this time, I was unsure of where to begin. As part of my efforts to enhance my frontend development skills, I undertook The Odin Project and worked on a calculator project. U ...

What is the best way to retrieve all dates that are older than 30 days using JavaScript?

I have the following code snippet as a reference and I'm attempting to retrieve a list of dates from 30 days before. What do I need to change? Date.prototype.addDays = function(days) { var newDate = new Date(this.valueOf()) newDate.s ...

Is there a way for the remaining divs in a column to match the width of the widest div?

I'm attempting to ensure that the divs in a column take the width of the widest element, with the exception of the top div which should span 100% of the screen. How can this particular layout be achieved? Please refer to the image below for a clear ex ...

Unleashing the power of ::ng-deep to access CSS in an Angular child component

I'm attempting to modify the CSS class of a child component by using ::ng-deep. Despite my efforts with various iterations of the code provided below, I have been unsuccessful in accessing the CSS. The structure of the HTML component is depicted in th ...

Enable the button if at least one checkbox has been selected

I've written some code similar to this: $('input[type=checkbox]').click(function(event) { $('.chuis').each(function() { if(this.checked) { $('#delete_all_vm').prop("disabled",false); } ...

Tips for breaking up array elements across multiple "tr" tags

In this particular example, I have a Fiddle set up with multiple tr elements displayed within an ng-repeat. My goal is to have three td elements per row. Would it be necessary to use an inner angularjs ng-repeat and split the iconDets array for this purpos ...