The following is my javascript code
class Sample {
constructor() {
this.btn = document.getElementById("btn");
this.score_display = document.getElementById("display");
this.current_container = document.getElementById("current_container);
this.next_container = document.getElementById("next_container);
this.scores = document.querySelectorAll(".scores")
this.finalScore; //final score
// Event listeners
this.eventListeners();
}
eventListeners() {
this.btn.addEventListener('click', () => {
this.next_container.classList.remove('hidden');
this.current_container.classList.add('hidden');
this.getScores();
});
}
getScores() {
this.scores.forEach(score => {
this. finalScore =
this.scores_display.innerHTML = this.score;
});
}
}
In the example code above, there are
- current container (rating app) - which has the rating/stars to be selected
- next container - that displays the selected rating/score from the current container
- When button is clicked, 'hidden' class is added to current container and removed from next.
- getScores() computes the scores and assigns to the finalScore
- Finallt, getScores() is called int he eventlistener.
The problem is, when I click btn(with eventlistener), the next_container, where the output of getScore() is to be stored, loads up very quickly before the getScore() is executed. This results in getScore() undefined.
I could manage this, by calling getScores() in the contructor so that it automatically is called, thus making a value of finalScore() available when the next_container is loaded.
How I can achieve this without the method called in the contructor
*** Edit ***
I have added the codepen link below