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

Switch Method (undefined being thrown)

Here I have a button I'm grabbing from the DOM, and I'm using a click event function that fires a switch to switch between states. The result should move a div around the screen, but nothing happens.

When i open the console I simply see:

undefined

What am I not defining here?

var stateLocation = 0;


document.getElementsByClassName('button')[0].addEventListener('click',function(){
  document.getElementsByClassName('box')[0]

  switch(stateLocation){
    case 0:
  if(box.classList.contains('three')){
    box.classList.remove('three');
  };
      stateLocation = 1;
      break;

    case 1:
      document.getElementsByClassName('box')[0].classList.add('one');
      stateLocation = 2;
      break;
    case 2:
      document.getElementsByClassName('box')[0].classList.remove('one');
      document.getElementsByClassName('box')[0].classList.add('two');
      stateLocation = 3;
      break;
      case 3:
      document.getElementsByClassName('box')[0].classList.remove('two');
      document.getElementsByClassName('box')[0].classList.add('three');
      stateLocation = 0;
      break;
  }

});

1 Answer

There is no assignment to a box variable.

The first line in the click handler should be refactored to:

var box = document.getElementsByClassName('box')[0];