Incorrect measurement of text size

My attempt at creating a basic font size changer was working perfectly until I integrated it with the bootstrap framework. Strangely, when I try to increase the font size, it actually decreases instead.

var baseFontSize;

(function () {
    "use strict";

    /*  Global variables */ 

    /*  jQuery Plugin: convert fontsize of a DOM element to em
    *
    *   usage: $( element ).pxToEm()
    *   returns a number rounded to 3 digits
    *
    */
    $.fn.pxToEM = function () {
        var fontSize = this.css("font-size"),
            value = /[^em|pt|px]*/g.exec(fontSize);
        return Number((value / baseFontSize).toFixed(3));
    };

}(jQuery));

$(document).ready(function () {
    "use strict";
    var body = $("#bodyid"),
        increaser = $("#font-sizer > ul > li:first-child"),
        decreaser = $("#font-sizer > ul > li:last-child"),
        maxFontSize = 2.0,
        minFontSize = 0.5;

    baseFontSize = parseFloat(body.css("font-size"));

    increaser.click(function (event) {
        var actualFontSize = body.pxToEM();
        actualFontSize += 0.1;
        if (actualFontSize > maxFontSize) {
            actualFontSize = maxFontSize;
        }
        body.css("font-size", actualFontSize + "em");
    });

    decreaser.click(function (event) {
        var actualFontSize = body.pxToEM();
        actualFontSize -= 0.1;
        if (actualFontSize < minFontSize) {
            actualFontSize = minFontSize;
        }
        body.css("font-size", actualFontSize + "em");
    });

});

I have included a link to a fiddle showcasing my code.

https://jsfiddle.net/uqrqo6bs/

Answer №2

EM as defined on MDN: The EM unit represents the calculated font size of an element. When used on the font-size property itself, it reflects the inherited font size of that element.

This implies that the font size in em for a specific element is determined by the font size of its parent.

In the provided example,

  1. The body font size is set at 14px
  2. The font size of #bodyid is 16px
  3. To determine the font size of #bodyid, em should be calculated based on its parent element, which in this case is 'body'. The fiddle uses #bodyid instead for the base font size. Switching to 'body' should resolve the issue.

Change needed:

baseFontSize = parseFloat(body.css("font-size"));

to

baseFontSize = parseFloat($('body').css("font-size"));

Answer №3

It is important to consider that not all sizes used in a document are necessarily using the same unit of measurement. For example, if the body has a font size of 1em and an element within it has a font size of 16px, a function like pxToEm may return 16(em).

Conversions should be based on the specific unit of the element.

For example, converting from (px) to (em) can be done as follows:

1em / 16px * (element font size in px) = resulting in em

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

What is the best way to position the wizard on both the left and right sides of the screen

Currently, here's the code I have, and I want it to appear like this. What are the steps needed to adjust the CSS in order to achieve that? .nav-wizard { display: table; width: 100%; } .nav-wizard > li { display: table-cell; text-align: ...

Removing HTML DOM elements from a string using JavaScript: A step-by-step guide

Hey there, I'm currently working on my angular application. When it comes to inserting the first 100 characters of content into the "description" meta tag for Facebook sharing, I've run into an issue. The description ends up including the HTML el ...

Making changes to the res object in an Express.js application

I came up with an innovative idea for the backend design of my single-page application website. My plan is to configure it so that any routes starting with "/api/" will return only the necessary data in JSON format, while all other routes will trigger a fu ...

Which one relies on the other: angular-data or angular-cache?

I'm struggling to get angular-cache set up properly. According to the documentation: Angular-cache is a dependency of angular-data and must be loaded before angular-data if you are using angular-data. That's all well and good, but what if I only ...

Unable to successfully create a dynamic anchor tag and open it in a new tab

I am receiving a PDF link in an AJAX response and I would like to manually trigger the download. Here is the code that I am currently using: var fileLink = document.createElement('a'); fileLink.href = responseData.PDF_LINK; fileLink.setAttribute ...

JavaScript - Merging the two JSON requests into a unified object

Is there a way to merge two different JSON responses into a single object for easy data manipulation? I've explored various solutions, but none seem to align with my current code structure. Given that I'm new to this, it would be incredibly hel ...

"Tree panel items in ExtJS 4 are displaying correctly in Firefox, but are mysteriously missing from

While working on my Tree Panel project, I encountered an issue with the display of items in different browsers. The items show up correctly in Firefox but appear empty in Chromium. How is this possible? Here's the JSON data sent to the server: {"tex ...

The functionality of jquery.load() seems to be experiencing issues in Internet Explorer when attempting to load an HTML file

Code $('.form').load('http://'+window.location.hostname+':8423/html/form/form_generate.html/?session='+session); In an attempt to load a html file from a different port on the same server. The original server is accessible ...

I encountered an error while trying to deploy my next.js project on Vercel - it seems that the module 'react-icons/Fa' cannot be found, along with

I'm currently in the process of deploying my Next.js TypeScript project on Vercel, but I've encountered an error. Can someone please help me with fixing this bug? Should I try running "npm run build" and then push the changes to GitHub again? Tha ...

What is the best way to retrieve a specific item from an array of objects stored in JSON format using React?

I have received a json file named data.json which contains multiple objects in an array. My goal is to extract the value of a specific key from each object. To achieve this, I am utilizing react redux to fetch these values and present them in a table forma ...

Broadcast and listen to events in AngularJS using `$rootScope.$emit`

I am currently working on a large Angular app and I have encountered the need to trigger an event using $rootscope.$emit, and then listen to this event inside a factory. Doing this inside a controller is not feasible because the controller hasn't load ...

In Google Chrome, the :after element on the left is cleared, while other browsers do not

In an effort to create a button using background images in the :before and :after pseudo-selectors for cross-browser compatibility, an issue arose where only Chrome did not display it correctly (Safari results were unknown). HTML: <div class="btn-cont ...

utilize JavaScript on every element that has a specific identifier

<a id="link" href="http://www.google.co.uk">link</a> <a id="link" href="http://stackoverflow.com">link</a> Is there a way to make the JavaScript code apply to all <a> tags with the id="link", instead of just the first one? A ...

Simple Steps to Convert an HTML String Array into Dynamic HTML with AngularJS Using ng-repeat

Below is an array consisting of HTML strings as values. How can I convert these strings into executable HTML code to display them? [ {html:'<button>name</button>'}, {html:'<table > <thead> <tr> <th>#</ ...

Incorrect Display of Datepicker Position

Trying to display a datepicker in a modal, but the output is not as expected: The datepicker is appearing in the wrong place. However, it works fine when testing on jsfiddle. Here is the link: http://jsfiddle.net/alverhothasi/D7bBg/ Currently using the ...

Experiencing difficulty in connecting with the service providers

What's the process for obtaining these providers? I recently followed the JavaScript Mastery tutorial step by step, however, I encountered an issue with the useEffect hook to fetch the providers (I even tried using alert to check, but it keeps showin ...

Delay the execution in selenium webdriver using Java until the login button is clicked manually

Can Selenium Webdriver be used to pause code execution with webdriver.wait until the user clicks the login button on a form? The form includes a Captcha that requires manual input, preventing automated clicking of the button by the script. Clicking the log ...

Having trouble getting static serving to work on Express.js when custom middleware is added

Seeking assistance with creating a middleware for my express js website to incorporate subdomains and serve static image, css, and js files. While my HTML pages load properly, I encounter long page load times and the javascript files fail to load. Any gui ...

ejs-lineargauge major divisions and minor divisions centered

I've been trying to align majorTicks and minorTicks in the middle of the axis, but so far I haven't found a solution despite searching and googling extensively. Here's a snippet of my code: majorTicks: { height: 12, interval: 1, width ...

Header rows in the table remain in place, however, the borders shift when viewed on Chrome and do not display at all on Firefox

I'm having trouble with the borders on my header table. In Chrome, the top border disappears when I scroll down, and in Firefox, it simply doesn't appear. You can see the issue here https://codepen.io/anon/pen/zyEwZq#anon-login Check it out on ...