I am trying to create a button that will add text when clicked. It works when the javascript is in the html file but does not when I link it externally.
HTML:
<input id="ex" type="text">
<button onclick="createList()">Create List</button>
<p id="demo">Click button</p>
<script src="app.js"></script>
Javascript:
document.addEventListener("DOMContentLoaded", () => {
function createList() {
var x = document.getElementById("ex").value;
document.getElementById("demo").innerHTML = x;
}
})
creatList()function in aDOMContentLoadedevent handler. Just add your<script>reference to the HTML page, right before the closingbodytag and the script need only contain yourcreateList()function. Also, the way your reference is set up,app.jsmust be in the same directory as the HTML page.