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.
4
Answers
Either remove
type="module"
since a module’s scope is private or addObject.assign(window, {change})
to yourscript.js
.Object.assign()
is used to assign several functions at once, could be useful later.But better use
addEventListener
…Your Javascript code is correct:
so referring the script is problematic. Remove the
type="module"
partJust an idea but it should probably work like this:
You may wanna go with "textContent" instead of "innerText" but that’s maybe just my preference, I dunno… and remember to style the button 🙂
I believe mixing old-timey HTML with modern JavaScript is a disservice to both. Why not keep both modern?
See Why are inline event handler attributes a bad idea in modern semantic HTML?, among others.