JavaScript does not function properly on dynamically loaded content from AJAX requests and it is not relying on

I am currently using ajax to load all content from 'mysite/math/' into math.php. I want to render the loaded math content using katex.

KaTeX GitHub

Inside math.php, I include the Katex library from the CDN mentioned in the link above.

The HTML structure of math.php:

<body>
  <div id='main'>
</body>

In the script tags within math.php, there is PHP code that retrieves a list of URLs from 'mysite/math/':

echo "var x = [];";
$dir = "./math/";
$a = scandir($dir);
foreach ($a as $x) {
if ($x === '.' or $x === '..') continue;
  echo "x.push('mysite/math/" . $x . "');";
}

This creates an array, x, containing the locations of each file's content to be loaded into the webpage.

To load the content, multiple AJAX calls are made to the URLs in the x array using JavaScript:

// defining the ajaxing function
function myfunction(url, someFunction) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
      someFunction(this, url);
    }
  };
  xhr.open('GET', url, true);
  xhr.send(null);
}

// defining the callback function
function callbackfunction(xhr, url) {
  var name = url;
  var div = document.createElement('div');
  div.innerHTML = xhr.responseText;
  div.className += name;
  document.getElementById('main').appendChild(div);
}

// executing the ajax calls
for (var i = 0; i < x.length; i++) {
  myfunction(x[i] + '?w=' + Math.random(), callbackfunction);
}

At this point, everything works smoothly.

The issue:

Within each HTML file in 'mysite/math/', there are span tags with the class='math' that hold the math content I intend to render. Despite observing these tags inside math.php, they do not render properly when accessed via ajax.

Furthermore, math.php includes JavaScript utilizing the katex function katex.render():

var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
  katex.render(math[i].innerHTML, math[i]);
}

The current usage of katex only functions correctly if the content is not being fetched via ajax.

Note: Many similar questions have been answered with jQuery solutions, but I specifically require a JavaScript solution.

Answer №1

If your AJAX-supplied content is not yet loaded on the page when katex.render is called by the browser, it's likely the cause of the issue.

To ensure that all your content loads before invoking katex.render, especially with multiple calls to load content, consider implementing one of the following methods using plain JavaScript:

  1. Set up an event listener that tracks the completion of each call. Once all calls have finished (you can keep count in a variable,) then call katex.render.
  2. Encapsulate each AJAX call within a promise, store them in an array, and utilize Promise.all on the array. Use Promise.all().then() to trigger katex.render after all promises have resolved.

Answer №2

I have come up with a simple solution that gets the job done well.

One change I made was to modify my callback function by adding a line applyKatex(div)

// Here is the updated callback function
function callbackfunction(xhr, url) {
  var name = url;
  var div = document.createElement('div');
  div.innerHTML = xhr.responseText;
  div.className += name;
  document.getElementById('main').appendChild(div);
  applyKatex(div); // This is the new addition
}

I also created a function called applyKatex() which takes an HTML element as input and applies the function katex.render() to every child-element with the class name 'math'

Now, whenever a new div is added to the page, katex.render() will automatically be applied to it as well

function applyKatex(element) {
  var math = element.getElementsByClassName('math');
  for (var i = 0; i < math.length; i++) {
    katex.render(math[i].innerHTML, math[i]);
  }
}

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

Display a fancy slideshow that transitions to five new images when the last one is reached

Here is a screenshot of my issue: https://i.stack.imgur.com/duhzn.png Incorporating Bootstrap 3 and FancyBox, I am facing an issue with displaying images in rows. When I reach the last image, clicking on the right arrow should result in sliding to anothe ...

The dialog box is not taking up the full width of the browser window

I'm facing an issue with a dialog box that only occupies a portion of the browser width, despite having a width set to 100%. The backdrop, however, extends across the entire width. //App.js import React from "react"; import ConfirmationDial ...

The website is having trouble reading the local json file accurately

Currently, I have developed an HTML site that utilizes JavaScript/jQuery to read a .json file and PHP to write to it. In addition, there is a C++ backend which also reads and writes to the same .json file. My goal is to transmit the selected button informa ...

Using jQuery Validation and AJAX to update a table row

I have created a table with an edit button for each row that triggers a bootstrap modal when clicked. The modal contains a form populated with information from the table. There is also a submit button on the modal to update the table data. To validate the ...

Exploring innovative designs for asynchronous JavaScript programming

Imagine you have an Express app and you need to retrieve data from a database to display on the frontend. There's a function in your code that looks like this (using node-mysql for handling database queries) exports.getData = function() { ...

Is it feasible to set a default value in an HTML input field that is not editable using JavaScript?

Is there a way to set a default value in an input field of HTML that is not editable, and then allow users to add additional text to it? For example, having 'AB' as the default and uneditable starting characters, followed by any numbers such as A ...

How to transform HTML input type with identical names into key-value pairs using jQuery

When the addmorefield button is clicked on this form, two more fields with the same name are appended: <form method="post" id="sampleform" action="#"> <div class="input_fields" style="text-align:center"> <input type="text" name="first_name ...

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 ...

Convert millimeters to inches with a unique AngularJS filter that activates on click

I am currently working on a UI that requires users to enter dimensions for width and height. Within the UI, there are 2 buttons available - one for 'mm' and the other for 'inches'. When either of these buttons is pressed, the active cl ...

In the realm of JavaScript and TypeScript, the task at hand is to locate '*' , '**' and '`' within a string and substitute them with <strong></strong> and <code></code>

As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>, and text surrounded by backticks with <code> </code>. I've implemented a ...

ES6 scoping confusion: unraveling the mystery

I stumbled upon these two syntax methods for exporting functions. Let's say we have files named actions.js and app.js. The first method looks like this: in actions.js export function addTodo() {} export function deleteTodo() {} and in app.js I have ...

Django: exploring the power of AJAX and HTTP requests

My English is not very good, but I am facing an issue with Django. Here are my models: class Model1(models.Model): model2 = models.ManyToManyField(Model2) #... class Model2(models.Model): model3 = models.ForeignKey(Model3) #... class Model ...

What is the most effective way to bring in "server-side only" code in Next.js?

I am currently working on my index page's getServerSideProps function and I want to utilize a function called foo, which is imported from another local file. This function relies on a specific Node library that cannot be executed in the browser becaus ...

Improve the Popup to seamlessly elevate

In my project, I have implemented a pop-up dialog box that rises up from the left bottom corner as the user scrolls down the page. You can view it live at this link- However, I am facing an issue where the initial lift up of the dialog box is not smooth, ...

The .keypress() function isn't behaving as expected

I've encountered a coding dilemma. Below is the code in question: $(document).ready(function () { var selectedDay = '#selected_day'; $(function () { $("#date").datepicker({ dateFormat: "DD, d M yy", a ...

Discovering the Essence of AngularJS Test Runner: Unraveling the

I recently started learning Angular JS and decided to follow the tutorial here. I've encountered a roadblock in step 8 where I need to write a test to check if the thumbnail images are being displayed. The concept behind it is simple. There is a JSON ...

Showing the Datepicker from jQuery right in the middle of the screen

Here's the generated code as default: <div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper- clearfix ui-corner-all ui-datepicker-multi ui-datepicker-multi-2" style="width: 34em; position: absolute; left: ...

Error: The Tabs component is expecting a different `value`. The Tab with the current `value` ("0") is not present in the document structure

I am encountering an issue while using MUI tabs. The error message I receive is as follows: MUI: The value assigned to the Tabs component is not valid. The Tab with this value ("0") does not exist in the document layout. Please ensure that the tab item is ...

Identify the externally-sourced element of interest

I'm attempting to apply a ScrollReveal effect to an element loaded from a separate html file called "header.html". Unfortunately, the ScrollReveal animation is not working on this particular element, while other elements within my index.html are funct ...

Develop a JavaScript application that contains a collection of strings, and efficiently sorts them with a time complexity of O(nlog n)

Seeking assistance in developing a JavaScript program that contains an array of strings and must sort them efficiently in O(nlog n) time. Grateful for any guidance... ...