Reputation: 17
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;
}
})
Upvotes: 0
Views: 86
Reputation: 704
createList is inside another function (arrow function of addEventListener), so it is not accessible in your html.
put it out of addEventListener
or another way - do onclick attachment inside addEventListener
, not in html, like:
document.addEventListener("DOMContentLoaded", () => {
document.getElementById('myButton').onclick = function() {
var x = document.getElementById("ex").value;
document.getElementById("demo").innerHTML = x;
}
});
Upvotes: 1
Reputation: 113
By declaring your createList()
function inside the event callback, you are actually scoping this function to the callback itself. You can just declare it as a function in your base javascript and it should be all good.
Before :
document.addEventListener("DOMContentLoaded", () => {
function createList() {
var x = document.getElementById("ex").value;
document.getElementById("demo").innerHTML = x;
}
After :
function createList() {
var x = document.getElementById('ex').value;
document.getElementById('demo').innerHTML = x;
}
If you want to wait for the DOM to be loaded before you declare your function, then you should attach your listener inside of the event callback like this :
document.addEventListener("DOMContentLoaded", () => {
document.getElementById('myButton').onclick = function() {
var x = document.getElementById('ex').value;
document.getElementById('demo').innerHTML = x;
}
});
Upvotes: 2
Reputation: 55
You can do this
<input id="ex" type="text">
<button onclick="createList()">Create List</button>
<p id="demo">Click button</p>
<script src="app.js"></script>
APP.JS
function createList() {
var x = document.getElementById("ex").value;
document.getElementById("demo").innerHTML = x;
}
Upvotes: 1