Reputation: 208
As you can see, I try to make two input buttons (one is shown, the other is hidden) that when clicked, displays the other and hides itself. btn
displays a canvas as well as btn2
when clicked but btn2
's onclick
method doesn't run.
var btn = document.getElementById("btn");
var btn2 = document.getElementById("btn2");
btn2.style.display = "none";
btn.onclick = function () {
btn.style.display = "none";
btn2.style.display = "block";
document.body.innerHTML += '<canvas id="someId"></canvas>';
};
btn2.onclick = function() {
btn2.style.display = "none";
btn1.style.display = "block";
document.getElementById("someId").remove();
};
canvas {
border: 1px dotted black;
}
<input id='btn' type="submit" value='REMOVE THAT!!!'></input>
<input id="btn2" type="submit" value="return to menu" display="none"></input>
Upvotes: 1
Views: 1381
Reputation: 64526
The problem is with this line:
document.body.innerHTML += '<canvas id="someId"></canvas>';
You're appending to the HTML of the body, which is bad practice because it has to re-render all elements and as such, you've lost the click handler for btn2.
The solution is to append the canvas as an element like so:
var canvas = document.createElement('canvas');
canvas.id = 'someId';
document.body.appendChild(canvas);
Now, the browser will append the canvas without destroying and recreating any other elements.
Also, you used btn1
which does not exist, change to btn
.
var btn = document.getElementById("btn");
var btn2 = document.getElementById("btn2");
btn2.style.display = "none";
btn.onclick = function () {
btn.style.display = "none";
btn2.style.display = "block";
var canvas = document.createElement('canvas');
canvas.id = 'someId';
document.body.appendChild(canvas);
};
btn2.onclick = function() {
btn2.style.display = "none";
btn.style.display = "block";
document.getElementById("someId").remove();
};
canvas {
border: 1px dotted black;
}
<input id='btn' type="submit" value='REMOVE THAT!!!'></input>
<input id="btn2" type="submit" value="return to menu" display="none"></input>
Upvotes: 1