Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this:

"document.body.style.fontSize = 100/50/20"

However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for the user as they may lose their place in the text.

Is there a way to ensure that the user remains at the same location in the text even after changing the font size?

Answer №1

If you're looking to give your user the ability to switch back and forth between different font sizes, incorporating javascript into your code is a necessity.

The use of document.body.style.fontSize only allows for increasing the font size without providing a way to revert it back to its original state.

var enlargeFont = false ;
function adjustFontSize( )
{
  textToResize = document.getElementById( 'text' );
  if (!enlargeFont) {
  // set desired size when button is clicked //
    textToResize.style.fontSize = "150%" ; 
    enlargeFont = true ;
  }
  else {
   // return font size to default on subsequent clicks //
    textToResize.style.fontSize = "100%" ;
    enlargeFont = false ;
  }
}
<button type="button" onclick="adjustFontSize();">Change Font Size</button>

<p id="text">lorem ipsum </p>

Answer №2

Based on your query, it seems like you are looking to maintain the scroll position after changing the font size.

I believe this solution will meet your requirements.

        //calculate scroll position as a percentage
        var totalScrollHeight = document.documentElement.scrollHeight;
        var currentPos = window.scrollY;
        var scrollPercent = Math.round((currentPos/totalScrollHeight)*100);
        
        //adjust font size
        document.body.style.fontSize = '15px';

        //reposition scroll to original area
        var updatedScrollHeight = document.documentElement.scrollHeight;
        var updatedClientScroll = (updatedScrollHeight * scrollPercent)/100;
        window.scrollY = updatedClientScroll;

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

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

Buffering ceases on the video

I am experiencing an issue with 4 videos and a preloader, which should hide once all the videos are fully buffered. <div id="preload"> <h1> Download... </h1> </div> <video preload="auto" class= ...

Unable to modify text color after implementing mat-sort-header in Angular Datatable

My current setup involves using an Angular data table to display data. I recently added the mat-sort-header functionality, which allowed me to change the font color of the header text. Below is a breakdown of my code: <section id="main-content" ...

The $postLink() method in the controller is encountering a null value for this.$scope

class pageController { constructor($scope, MyEditableGrid) { this.$scope = $scope; this.MyEditableGrid = MyEditableGrid; this.myEditableGrid = { appScope: this.$scope, ..... } } $postLink ...

What is the method for displaying the value of a textarea?

I am relatively new to the world of coding, but I have already delved into HTML, CSS, and basic DOM scripting. My goal is simple - I want to create a comment box where people can leave messages like in a guestbook. However, when I input text and click on ...

Accessing store in Vue, the getter function returns a value representing whether the user is currently logged

I have the user state stored in my Vue store, but when I try to access it like this: let isLoggedIn = store.getters.isLoggedIn Instead of getting a simple true or false, I see this in the console: ƒ isLoggedIn (state) { return state.user ? true : false ...

How to Send an Array to AJAX and Retrieve the Data in Codeigniter Controller

I am attempting to retrieve table data, store it in an array, and pass it to the controller so I can write it in PHP Excel. Previously, I had success with other data but now my excel file is turning up empty. Below is the JavaScript code snippet: var Ta ...

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...

Combine multiple SCSS files located in various directories into a single CSS file by using NPM

In my project, there are SCSS files stored in a "static" directory. Additionally, I have application components located in a separate directory, each containing its own SCSS file. I am seeking a way to compile all of these SCSS files into a single .css fi ...

`Check out Vue3's property watching feature`

Currently, I have a form that is being edited and the created method is used to prefill the form information from an api call, which works perfectly fine. However, my goal is to monitor the fields in the form. If any of them are edited, I want to set a va ...

Get a URL from the JSON data returned by the Wikipedia API

How can I retrieve the image URL from a JSON response and store it in a variable? I found helpful information on the MediaWiki API help page Following this example to extract image information from a page: https://commons.wikimedia.org/w/api.php?action= ...

What is the best way to ensure all table rows have consistent heights that are not affected by image sizes?

In the provided code snippet, you will notice that the height of the table rows varies slightly based on the height of the images. Currently, the image tags are set to height: auto;, and changing it to 300px would make all images the same size, however, m ...

How do I pass input values when calling an AJAX function to submit a form in HTML?

Utilizing a modal to submit new data via AJAX API consumption. Although sending the data through the API is not an issue, my lack of HTML skills makes it confusing on how to pass form data values. This scenario involves displaying a modal for users to in ...

Position a dynamic <div> in the center of the screen

My goal is to design a gallery page with a list of thumbnails, where clicking on a thumbnail will open the related image in a popup div showing its full size. The issue I'm facing is how to center the popup div on the screen, especially when each pic ...

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

We apologize, but the module you are looking for cannot be found: Unable to locate 'fs'

Trying to create a new MDX blog website using Next.js 13 with the latest app router, but encountering an error message saying "Module not found: Can't resolve 'fs'". It was working fine in Next.js 12 and pages directory, but not in the lates ...

The jQuery datetimepicker fails to reflect changes made to the minDate property

I have encountered a datetimepicker object that was previously set up with the following configuration: $('#startDate').datetimepicker({ monthNames: DATE_TIME_MONTHS_NAMES, monthNamesShort: DATE_TIME_MONTHS_NAMES_SHORT, dayNames: DAT ...

Javascript/Typescript Performance Evaluation

I am looking to create a visual report in the form of a table that displays the count of each rating based on the date. The ratings are based on a scale of 1 to 5. Below is the object containing the data: [ { "Date": "01/11/2022", ...

The ng-controller is not functioning properly even when being correctly invoked

I tried out some simple angularjs code, utilizing nodejs, angularjs, and html. Here are my files: https://github.com/internial/test. I decided not to include the node_modules folder as it was too large. On localhost:8080, this is the result: {{1 + 64}} ...

The script is malfunctioning on Google Chrome

Below is a script that I have: EXAMPLE : <script> var ul = document.getElementById("foo2"); var items = ul.getElementsByTagName("li"); for (var i = 0; i < items.length; i=i+2) { // perform an action on items[i], which repr ...