So I was trying to make a really basic script, when someone clicks on a button some text would appear. The problem is that if I use document.addEventListener('DOMContentLoaded') and put the script in it, then I get this error: "Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick")
document.addEventListener("DOMContentLoaded", function() {
function myFunction() {
var x = document.createElement("B");
var t = document.createTextNode("Some bold text");
x.appendChild(t);
document.body.appendChild(x);
}
});
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click the button to create a B element with some text.</p>
<button onclick="myFunction()">Try it</button>
<script src="jquery.js"></script>
<script src="js.js"></script>
</body>
</html>
^This doesn't work. If I change the JS to:
function myFunction() {
var x = document.createElement("B");
var t = document.createTextNode("Some bold text");
x.appendChild(t);
document.body.appendChild(x);
}
it does. Can you explain to me what's happening? I can't really get it.