I browsed the other answers but couldn't find a solution for this problem.
I have this HTML:
<body>
<h1>Javascript in the Browser</h1>
<div id="removeReference">
</div>
<div>
<p>This page looks a little sad without any style...</p>
<button id="styleButton">Apply some style!</button>
</div>
<div id="imagePlaceholder">
</div>
<script src="script.js"></script>
</body>
In the JavaScript file, I have a function stylePage
that is triggered by clicking a button and it adds some style, removes the button itself, and creates a new button.
At this point, I'd like to add an event to this dynamically created new button so that when clicked the function createImage
is triggered.
I know it's be better to use libraries but this is an attempt at self learning JavaScript.
I thought that maybe it was possible to return the button from stylePage
and add the event listener to the return value but that didn't work.
Any suggestion is much appreciated, thanks!
function stylePage(){
var body = document.getElementsByTagName("body");
body[0].style.backgroundColor = "rgb(214, 214, 214)";
body[0].style.color = "#778899";
body[0].style.fontFamily = "Courier";
body[0].style.textAlign = "center";
var remove = document.getElementById("removeReference");
remove.nextElementSibling.remove();
var newButton = document.createElement("button");
var newContent = document.createTextNode("Not enough?");
newButton.appendChild(newContent);
document.body.insertBefore(newButton, remove);
};
function createImage(){
var img = document.createElement("img");
img.src = "pepsi_dog_by_werelyokoman.jpg";
document.getElementById("imagePlaceholder").appendChild(img);
}
var button = document.getElementsByTagName("button");
button[0].addEventListener("click", stylePage);
//??? reference to newButton ??? .addEventListener("click", createImage);