I’ve simplified the code to handle the same function (handlestartbuttonpress) for simplicity and debugging sake. When the "start button" is pressed, everything works as expected, a short delay before updating the page and rendering the page with the content for "a". but on the "a" page, the option 2 div element should reload to the "b" page. but i get nothing.
I’ve tried different ways of calling the function including onclick rather than event listeners, same result.
let score = 0;
let op1 = '';
let op2 = '';
let op3 = '';
let opc = '';
let nxt = '';
function reload(rp) {
if (rp === '') {
document.getElementById('container').innerHTML =
`<div id="startbuttoncontainer"><img id="startbutton" src='assets/startbutton.png' /></div>`;
}
if (rp === 'score') {
document.getElementById('container').innerHTML =
`<span>Final Score<br/>${score}</span>`;
}
if (rp === 'a') {
op1 = 'Red';
op2 = 'Apple';
op3 = 'Tree';
opc = '2';
nxt = 'b';
document.getElementById('container').innerHTML =
`
<div id="paperbg">
<span id="score">Score: ${score}</span>
<img id="obj" src="assets/${rp}.png" />
</div>
<div id="opscontainer">
<div id="op1" class="op">${op1}</div>
<div id="op2" class="op">${op2}</div>
<div id="op3" class="op">${op3}</div>
</div>
`;
}
if (rp === 'b') {
op1 = 'Blue';
op2 = 'Bunny';
op3 = 'Banana';
opc = '3';
nxt = 'c';
document.getElementById('container').innerHTML =
`
<div id="paperbg">
<span id="score">Score: ${score}</span>
<img id="obj" src="assets/${rp}.png" />
</div>
<div id="opscontainer">
<div id="op1" class="op">${op1}</div>
<div id="op2" class="op">${op2}</div>
<div id="op3" class="op">${op3}</div>
</div>
`;
}
}
function handlestartbuttonpress(p) {
// document.getElementById('startbuttoncontainer').innerHTML =
// `<img id="startbuttonpressed" src='assets/startbuttondown.gif' />`;
setTimeout(function() {
reload(p);
}, 1600);
}
reload('');
document.getElementById('startbutton').addEventListener("click", function() {
handlestartbuttonpress('a');
});
document.getElementById('op2').addEventListener("click", function() {
handlestartbuttonpress('b');
});
<div id="container"></div>
2
Answers
I think the issue here is that you are adding the even listener too early.
SetTimeout make the
a
part render after 1600 ms while you are adding the event listener beforea
has rendered.Thus
op2
element does not exist when you are adding the event listener.You need to delegate.
Here is a cleaner version