Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Object-Oriented JavaScript (2015) Practice Project Project Overview

Kostas Koutoupis
Kostas Koutoupis
15,010 Points

Can't update question on click

This is my code

//create Question
function Question(text, correct, mistake){
 this.text = text; 
 this.correct = correct;
 this.mistake = mistake;
}

//create QuestionSet
function QuestionSet(){
 this.questions = [];
 this.currentQuestion = 0;
 this.add = function(question){
  this.questions.push(question); 
 }
}

//add display functionality to questionSet
QuestionSet.prototype.displayQuestion = function(){
  var container = document.getElementById("question"),
      correctContainer = document.getElementById("choice0"),
      wrongContainer = document.getElementById("choice1");

  container.innerHTML = this.questions[this.currentQuestion].text;
  correctContainer.innerHTML = this.questions[this.currentQuestion].correct;
  wrongContainer.innerHTML = this.questions[this.currentQuestion].mistake;
}


//move to nextQuestion
QuestionSet.prototype.nextQuestion = function(){
  this.currentQuestion++;
  if(this.currentQuestion===this.questions.length){
   this.currentQuestion=0; 
  }
  this.displayQuestion();
}


//create questions
var q1 = new Question("What\'s my name?", "Jim", "Bob");
var q2 = new Question("What\'s my surname?", "Smith", "Johnson");
var q3 = new Question("What\'s my favourite snack?", "Chocolate", "Apples");

//create new QuestionSet
var set = new QuestionSet();

//add questions to QuestionSet
set.add(q1);
set.add(q2);
set.add(q3);

//display current Question
set.displayQuestion();



//update question on click
var button = document.getElementsByClassName('btn--default');
for(var i=0; i<button.length;i++){
 button[i].addEventListener('click',set.nextQuestion); 
}

When i run set.nextQuestion() in the console, everything is updated on the page. However, when I click on the buttons, nothing happens. Any ideas? Thanks!!!!

1 Answer

Steven Parker
Steven Parker
218,691 Points

The event listener establishes "set.nextQuestion" as the handler function, and inside the function "this" is used as a reference to the "Questionset" object.

However, when an event handler is invoked, "this" is assigned to the element which triggered the event instead. So the handler code fails.