A "bug" with Javascript

Hello!

First I wish you a happy new year! All the bests!

I am still using Prodigy for experiments purposes, and I encountered a problem while using the view_id "html" and javascript.

My goal is to make people choose an order for videos, and I would have liked to implement a drag and drop option (like "sortable" with jquery) to make the experiment more comfortable and intuitive. I started with testing available snippets of codes, and drag and drop examples I found online didn't work if launched with Prodigy while they worked if the html was opened individually, so I did easier tests.

I did an easy example to check something:

My HTML body contains only a div with the id "mydiv". Then in the Javascript, I only wrote the command:

"document.getElementById("mydiv").innerText = "text"; (it's not in any function)

when I launch Prodigy on local and watch the log I have the following message:
"Uncaught TypeError: document.getElementById(...) is null" meaning that mydiv is null thought it does exists.

My guess is that Javascript is launched before all the page is loaded so it doesn't detect "mydiv", but I wonder why there is such a behaviour.

Thanks in advance for your answer,

Bests,

Estelle

Hi! Your analysis is correc: this error typically happens when the JavaScript is executed before the markup is available. In a normal app, you'd typically listen for an event like DOMContentLoaded to be fired so you know when the DOM is ready. In the context of Prodigy, there are other factors that have an impact on when the content is loaded, so Prodigy fires a custom event prodigymount when the app has mounted and is ready (see the section of custom events here).

So in your code, you can do the following to make sure it's only executed when Prodigy is ready and has rendered your custom HTML:

document.addEventListener('prodigymount', () => {
    const myDiv = document.getElementById('mydiv')
    // your code here...
})
1 Like

Hi,

Thank you so much for your fast answer!
It solved my problem!

1 Like