Reputation: 31
I have this example code and the button is not clickable, I got this error when I click on it
also when open the source code I can see two buttons why?
Uncaught ReferenceError: addText is not defined onclick file:///C:/Users/Dany/Desktop/javatest/index.html:1
<body data-new-gr-c-s-check-loaded="8.867.0">
<div id="button"><button onclick="addText()">Add Text</button><button></button>
</div>
<div id="printData"></div>
</body>
Now this is my code, and please noticed that I need the button to be inside the js not in html and thanks
window.addEventListener("load", function() {
let btn = '<button onclick="addText()">Add Text<button/>';
let data = document.getElementById("printData");
let info = document.getElementById("button");
info.innerHTML = btn;
function addText(){
data.innerHTML = "Hello World!";
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<link href="css/css.css" rel="stylesheet">
<script src="js/js.js">
</script>
</head>
<body>
<div id="button"></div>
<div id="printData"></div>
</body>
</html>
Upvotes: 0
Views: 534
Reputation: 5202
Try something like this
window.addEventListener("load", function() {
let btn = '<button>Add Text</button>';
let data = document.getElementById("printData");
let info = document.getElementById("button");
info.innerHTML = btn;
info.addEventListener("click", () => {
data.innerHTML = "Hello World!";
})
});
Upvotes: 1
Reputation: 101
the function must be outside of the event listener
window.addEventListener("load", function() {
let btn = '<button onclick="addText()">Add Text<button</button>';
let info = document.getElementById("button");
info.innerHTML = btn;
});
function addText(){
let data = document.getElementById("printData");
data.innerHTML = "Hello World!";
}
<div id="button"></div>
<div id="printData"></div>
Upvotes: 0