Search code examples
javascripthtmlstackblitz

Calling a function from an external JavaScript file in HTML


I'm learning HTML and practicing in the StackBlitz in-browser IDE. I'm trying to use a element's onclick to change the text of a <p> element, but nothing's happening when I click the button.

Code in the index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Home</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" href="styles.css" />
    <script type="module" src="script.js"></script>
  </head>

  <body>

    <p id="words">Starting Text</p>
    <button onclick="change()">Change Words</button>

  </body>

</html>

Code in the script.js file:

function change() {
  document.getElementById("words").innerText = 'Words Have Been Changed';
}

index.html and script.js are both in the root folder in the StackBlitz project directory.

I don't know if there's an obvious syntax blunder I'm missing, or if there's something I don't understand about the StackBlitz IDE, or something else. I tried assigning the alert() function to onclick, as well as custom functions defined in the HTML, and those all worked. It's just when the assigned function is from the script.js file that nothing happens.


Solution

  • Either remove type="module" since a module's scope is private or add Object.assign(window, {change}) to your script.js. Object.assign() is used to assign several functions at once, could be useful later.

    <script type="module">
    function change() {
      document.getElementById("words").innerText = 'Words Have Been Changed';
    }
    Object.assign(window, {change});
    </script>
    <p id="words">Starting Text</p>
    <button onclick="change()">Change Words</button>

    But better use addEventListener...