I have some HTML buttons. One labeled "Next", one labeled "Back". Each should call their respective function on click.
HTML
<div class="buttons">
<button class="lastQuestion">Back</button>
<button class="nextQuestion">Next</button>
</div>
JS
function nextQuestion() // not including full code inside function
function lastQuestion() // not including full code inside function
I am iterating over the buttons and listening for clicks. I am calling the function depending on their text content. This only works when I specifiy const
for each iteration. If I don't, both buttons call nextQuestion()
. I haven't tried this with let
, but I would like to know why this is the case in JavaScript? I'm new to JS specifically.
This works:
for (const btn of navButtons) {
btn.addEventListener('click', () => {
if (btn.textContent === 'Next') {
nextQuestion();
} else {
lastQuestion();
}
})
}
This does not:
for (btn of navButtons) {
btn.addEventListener('click', () => {
if (btn.textContent === 'Next') {
nextQuestion();
} else {
lastQuestion();
}
})
}