Run js scripts on dynamically loaded ejs partials

Viewed 16

I'd like to attach several js functionalities to an ejs partial rendered by an express server on an XMLHTTPRequest, but I don't manage to get any javascript code to run.

Here a simplified example:

-- partial.ejs --
<div>
  <h3>Loaded</h3>
  <button id='play'>PLAY</button>
</div>
<script type="text/javascript">
  console.log("my new script!");
</script>
<script src='js/newFunctions.js'></script>

After receiving the ajax call, the server correctly renders the partial, including the script tags, but nothing is logged in the console.

The content of newFunctions.js adds an EventListener to the <button> and declares a few functions:

-- newFunctions.js --
const btn = document.getElementById('play')

function goOn(){
  console.log('Ready to Play')
}

btn.addEventListeners('click', goOn)

but the button does not respond to click and even if I declare the event onclick='goOn()' inside the tag, the console throws goOn is not defined.

I tried loading the script from the page in which partial.ejs is loaded, but of course, btn results in undefined.

In this specific example I could probably declare goOn() in partials.ejs's "parent" page, but I'd like to take this opportunity to ask you:

What is the best practice to add javascript functionalities to a dynamically loaded ejs file?

Or is there a way to make the parent page aware that partial.ejs has been rendered, i.e. new elements have been added to the page?

Thank you!

0 Answers
Related