Skip to content Skip to sidebar Skip to footer

Why Won't This Simple Event Listener Work In Javascript?

I was wondering if someone could provide a teaching point for me. I am trying to learn Javascript and the logic of this code seems reasonable to me, but it doesn't work for some re

Solution 1:

The other answers failed to notice the reason for the question which is to understand why it doesn't work.

The reason why it doesn't work is because of how JavaScript gets executed.

var myvar; // myvar is declared, but not defined yet. myvar === undefinedfunctionfoo(){
  myvar = true;
  console.log('EVENT!');
}

// obviously at this point, `foo` has just been declared, not called/executed.

myButton.addEventListener('click', foo);
// foo still hasn't been executed. It has been assigned as handler to be executed whenever a click event is firedswitch(myvar) {  // myvar is still undefined, because foo hasn't been executed
  ...
}

window.setTimeout(function(){
  console.log('Checking myvar');
  console.log(myvar);
}, 5000); // the function defined here will be called after 5 secnds/* time passes, mouse is clicked */// now foo is executedEVENT!
/* 5 seconds have passed, the function in setTimeout is executed */Checking myvar
true

Solution 2:

The switch must be inside the function of the event Listener:

myButton.addEventListener("click", function() {
    testingVar = "hello";
    switch (testingVar) {
      case"hello" :
        alert("You've got the hello condition!");
        break;

      case"goodbye" :
        alert("You've got the goodbye condition");
        break;
    } // end switch statement
}, false);

In your example, the variable testingVar is initalized, but has no value assigned when the switch part of the code is executed.

Also, if you had defined a default case, you would have recognised that the switch is called on pageload.

Solution 3:

Try this:

<script>var myButton = document.getElementById("myButton");
    var testingVar;


myButton.addEventListener("click", function() {
    testingVar = "hello";

    switch (testingVar) {
        case"hello" :
            alert("You've got the hello condition!");
            break;

        case"goodbye" :
            alert("You've got the goodbye condition");
            break;
    } // end switch statement

}, false);


</script>

As a side note, it's usually better to put your script tags in the head of your html.

Post a Comment for "Why Won't This Simple Event Listener Work In Javascript?"