Improper height of MathJax in the div element

I'm currently investigating why the MathJax render block is giving me an incorrect height for the div. Here's the code snippet:

<div class="text-field" id='inner-text'>\(\sqrt{b^{a}\frac{\partial y}{\partial x}}\)</div>

Here's the associated CSS:

.text-field {
    display: inline-block;
    overflow: hidden;
    max-width: 15em;
}

When executing the following JavaScript snippet:

  MathJax.typeset();
  let text = document.getElementById("inner-text");
  console.log(text.clientHeight,
              text.offsetHeight,
              text.getBoundingClientRect().height,
              window.getComputedStyle(text).getPropertyValue('height'));

The console outputs:

41 41 41.25 "41.25px"

However, upon inspection in the elements tab:

https://i.sstatic.net/wWhjD.png

The actual height doesn't match any of the height values retrieved via JS. What could be causing this discrepancy and how can I obtain an accurate height value?

Answer №1

The issue arises from the time taken by MathJax to generate the visualization. My solution involves allowing MathJax sufficient time to process before determining the size of the element.

I have developed two versions of the code, both functioning correctly across various browsers such as Firefox, Chrome, and Edge.

Method 1:

This script waits for MathJax to load, then provides an additional 100ms for it to finalize before calculating the dimensions of the inner-text.

var checkEx = setInterval(function () {
    let wrap = document.getElementById("inner-text");
    var text = wrap.getElementsByClassName('MathJax')[0];
    if (text) {
        setTimeout(() => {
            console.log(wrap.getBoundingClientRect().height, wrap.getBoundingClientRect().width);
        }, 100);
        clearInterval(checkEx);
    }
}, 100);
.text-field {
    display: inline-block;
    overflow: hidden;
    max-width: 15em;
}
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>


<div class="text-field" id='inner-text'>\(\sqrt{b^{a}\frac{\partial y}{\partial x}}\)</div>


Method 2

This script also waits for MathJax to load and then starts measuring the dimensions of the element. Once the dimensions stabilize, it returns the size of the inner-text.

var elhg;
var elwg;

var checkEx = setInterval(function () {
    let wrap = document.getElementById("inner-text");
    var text = wrap.getElementsByClassName('MathJax')[0];
    if (text) {

        elHeight = wrap.getBoundingClientRect().height;
        elWidth = wrap.getBoundingClientRect().width;

        if (elhg === elHeight && elwg === elWidth) {
            console.log(elHeight, elWidth);
            clearInterval(checkEx);
        }

        elhg = elHeight;
        elwg = elWidth;
    }
}, 100);
.text-field {
    display: inline-block;
    overflow: hidden;
    max-width: 15em;
}
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

<div class="text-field" id='inner-text'>\(\sqrt{b^{a}\frac{\partial y}{\partial x}}\)</div>

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

The background color of social media links spills over onto other links, creating a messy overlap

I have been trying to confine the teal hover effect within the boundaries of my social media links. Despite adjusting padding, heights, and widths using CSS properties, the hover effect still extends beyond the right border. Here is how it appears without ...

AngularJS ui-router, html5Mode, and Express causing "Cannot GET" error in nested state

Currently, I am facing an issue while trying to implement $locationProvider.html5Mode(true) with AngularJS, ui-router, and ExpressJS. The problem arises when navigating to a nested state parent.child with URL /child, as refreshing the page or directly typi ...

npm ERROR! 404 Content removed by unidentified source on August 8, 2022 at 09:20:35.527 UTC

Upon running the command <npm view e-biz-znnf versions --json> in the terminal, npm throws an error message: npm ERR! code E404 npm ERR! 404 Unpublished by undefined on 2022-08-08T09:20:35.527Z npm ERR! 404 npm ERR! 404 'e-biz-znnf' is no ...

Expand the video comparison slider to occupy the entire width and height

I am striving to develop a video comparison slider that fills the height and width of the viewport, inspired by the techniques discussed in this informative article: Article Despite my efforts, I have not been successful in achieving this effect so far a ...

How can I collapse the dropdown menu in typeahead.js?

I am currently utilizing typeahead.js for a typeahead functionality. My goal is to achieve the opposite of what was discussed in this thread: Programmatically triggering typeahead.js result display Despite attempting to trigger a blur event on the typeah ...

When you drag and drop multiple items, the entire data set is erased

I am currently working on a grid that loads data from a JSON file in a React application. When a user holds down the ctrl key on an item, that item is tagged with a new property called selected. My goal is to enable the user to drag and drop the tagged ite ...

The issue with Nextjs getStaticPaths is that it is not retrieving data from Firebase Firestore

I'm encountering an issue with fetching dynamic data from firestore in nextjs using getStaticPaths. While rendering the data from firestore with getStaticProps works, I'm facing a problem when trying to access specific item details as it leads me ...

Finding the perfect regex pattern to extract bank transaction information

My goal is to automate the process of reading and extracting information from my monthly bank document that contains all transactions. Currently, I manually input all transactions into an Excel spreadsheet, but I would like to streamline this task. This af ...

A unique technique for creating a stunning visual effect with images using

Can anyone help me with this issue: Check out this animated GIF The images in my project are overlapping when scrolling! How can I achieve a similar effect for my images? Is there a tutorial or plugin available for this? Here is the current code sn ...

Capturing C# log data for JavaScript interactions

Can anyone provide recommendations on how to capture JavaScript interactions in a browser using C#? I am interested in developing a web crawler that can track these interactions, allowing me to search for potentially harmful calls. ...

Pass a selected object to a dropdown/select change event using AngularJS

Plunkr : http://plnkr.co/edit/BRQ3I4hFTlgKq4Shz19v?p=preview I'm attempting to pass the selected item from a dropdown to a function within my controller. Unfortunately, I keep receiving it as undefined. HTML : <!DOCTYPE html> <html> ...

In Javascript, determine the root cause of a boolean expression failing by logging the culprit

Within my JavaScript code, I have a complex predicate that comprises of multiple tests chained together against a value. I am looking for a way to log the specific location in the expression where it fails, if it does fail. Similar to how testing librarie ...

What is the best way to align icons in the center alongside text or paragraphs using react?

I'm struggling with centering my icons like <GrTools size="30px"/> next to my text. It's causing some alignment issues with my styled components. Here is my JavaScript: <div id='paragraph' className="container"> ...

Having trouble locating an element on a webpage? When inspecting the element, are you noticing that the HTML code differs from the source page?

I'm having trouble locating a specific element on a webpage. When I use the Inspect Element tool, I can see the HTML code with the element id = username, but when I check the page source, all I see is JavaScript code. Does anyone have any suggestions ...

The validation directive is run on each individual item within the ng-repeat loop

As I develop a single page application utilizing Angular and Breeze, the challenge of managing entities with dynamic validation arises. With a set of entities displayed on the page using data-ng-repeat, I implement in place validation through toggling betw ...

AngularJS - Retaining the initial value without submitting

On the left side, I have a list of users with corresponding details displayed on the right. The form handles the details on the right using inputs with ng-model. Whenever I click on a user from the left section, the selected user changes and the model auto ...

Trouble with Firebase/Firestore documentation queries in JavaScript

Having trouble using the new Firestore system. I'm trying to retrieve a Collection of all users and go through it, but I can't seem to make it work. db.collection("users").get().then(function(querySnapshot){ console.log(querySnapshot.dat ...

The React.js Redux reducer fails to add the item to the state

I'm just starting to learn about React.js and Redux. Currently, I am working on creating a basic shopping cart application. https://i.stack.imgur.com/BfvMY.png My goal is to have an item (such as a banana) added to the cart when clicked. (This sho ...

Use jquery ajax to upload an image with a reusable input field

UPDATE: Progress has been made in solving this issue. Please refer to Jquery form no submission to IE7 and IE8. The main task remaining is sorting out the compatibility with IE7 and IE8. I have been utilizing THIS plugin to upload files as email attachmen ...

Error Loading Collada Texture: Three.js Cross Origin Issue

I'm encountering an issue with loading a Collada file using three.js that has a texture called Texture_0.png associated with it. The Collada file and the texture are stored in the same blob and accessed via a REST Web Service. CORS is enabled, allowin ...