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

Adding static files to your HTML page with node.js

This is not a question about using express.static() In my application, I have multiple pages that share the same JS and CSS dependencies. Instead of adding <script> or <link> tags to every single page, I'm looking for a way to include the ...

A fresh javascript HTML element does not adhere to the css guidelines

While attempting to dynamically add rows to a table using Javascript and jQuery, I encountered an issue. Here is my code: <script> $(document).ready(function(){ for (i=0; i<myvar.length; i++){ $("#items").after('<tr class="item- ...

Executing a function immediately upon the start of a new month in JavaScript (Node.js) without relying on any external libraries?

Is it possible to automate the process of creating a document in MongoDB using Mongoose every 1st of a new month, ideally as soon as the date changes without relying on third-party libraries like needle or cronjob? Can this be achieved solely with setInter ...

The issue of memory leakage caused by jQuery Ajax requests

A problem has arisen on my website where memory is being leaked in both IE8 and Firefox. The Windows Process Explorer shows a continuous growth in memory usage over time. The issue arises when the page requests the "unplanned.json" URL, which is a static ...

Processing hover attributes in Tailwind-styled-components

I'm currently working on a website that features a dark mode, and I want to utilize the dark prop in tailwind-styled-components. The props work fine in all instances except for actions like hover, active, focus, etc. When attempting to use hover and t ...

The function is triggered only on resize, not on initial load

Is there a way to ensure that the carouselPartialView function runs automatically when the page loads? I've noticed that it doesn't run when directly called, but works fine when called with the resizeWitdthOnly function. How can I make sure it ru ...

Emulate the utf8_general_ci collation in mysql database

I am in the process of integrating a javascript application with a third-party API that manages names in a database. The challenge I am facing is that the third-party application uses utf8_general_ci collation to determine name uniqueness, while my applica ...

"Enhancing User Interaction with AngularJS: Leveraging ng-click and ng

Currently, I have a map with markers that trigger an overlay-div to open when clicked. <div class="map" ng-init="loadall()"> <a ng-click="details.show=!details.show" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker ...

Navigating a loop in javascript: tips and techniques

I have a challenge with three boxes that are supposed to fade in, shake, and then fade out. The IDs of each box are stored in an array and a loop is used to traverse them. However, the loop only displays the first item. I have tried various methods in Jav ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

When the app loads in AngularJS, make sure to call the jQuery plugin. Additionally, remember to call

In my AngularJS app, I have a need to call the following code: $('.nano').nanoScroller({ alwaysVisible: true }); This should be executed when the application loads and also when the state changes. In traditional non-angular applications, I wou ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

I'm having trouble with my basic routing set up and I'm struggling to understand why it's not working

I'm currently working on a node tutorial and facing some challenges with my routes.js file. Previously, everything was functioning well today as the Node server was able to read the file. However, it seems to be ignoring it now for some unknown reaso ...

Can JavaScript event listeners be compelled to trigger in a specific sequence?

Is there a way in JavaScript to receive notification or execute a callback function once an event has completed its propagation? Put differently, is it possible to 'prioritize' an event and ensure that it gets triggered after all other event lis ...

Tips for displaying lesser-known checkboxes upon clicking a button in Angular

I have a form with 15 checkboxes, but only 3 are the most popular. I would like to display these 3 by default and have an icon at the end to expand and collapse the rest of the checkboxes. Since I'm using Angular for my website, I think I can simply ...

What is the reason for not modifying the filtered and sorted data?

I am currently working on implementing filter options for an item list, but I am facing an issue where the filtering does not work when selecting dropdown options. Array in App.jsx const cameraShowList=[ {id:1,model:"Canon",title:"Canon ...

Preview not showing CSS changes properly

1) I am encountering an issue with displaying CSS in a form preview tab. Despite setting the CSS, it does not reflect on the fields after clicking the preview button. 2) Are there alternative methods to open the tab in a new window rather than opening it ...

Encountering weathers.map is not a function error while using React.js with OpenWeatherMap integration

Struggling with React.js for a college project and need some help. The error message I keep encountering is: weathers.map not a function I know it's probably something simple, but for the life of me, I can't figure it out! My project structure f ...

Trouble with disabling default actions and transferring text

When the user clicks on loginAccount, the intention is to extract the text from the element with the id input-1 and assign it to username. This same process should occur for password, followed by form submission. However, despite using e.preventDefault() ...

Touch Screen Button Interaction

Planning to create a Kiosk website with HTML5 that includes point and drag & drop functionality. The site will have buttons and images for user interaction, with actions triggered by finger touches on the screen instead of mouse clicks. Would it be more ...