0

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.

asked Jan 28, 2018 at 17:18
8
  • Is myFunction() within js.js? Commented Jan 28, 2018 at 17:20
  • Why did you put your function inside DOMContentLoaded? Commented Jan 28, 2018 at 17:21
  • Literally just answered this same question. Don't use onxyz-attribute event handlers. They can only call global functions. Commented Jan 28, 2018 at 17:21
  • @T.J.Crowder then how should my code look? Can you correct it? Commented Jan 28, 2018 at 17:22
  • @Musa as far as I know, that's good practice. I shouldn't do it with everything I think, though. Commented Jan 28, 2018 at 17:23

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.