Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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){

//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(){

//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

//display current Question

//update question on click
var button = document.getElementsByClassName('btn--default');
for(var i=0; i<button.length;i++){

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
229,657 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.