Reputation: 993
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 reason.
It's basically a button. I'm trying to make it so that when the button is clicked, the variable testingVar changes to one of the conditions of my switch statement. Yet when I click the button, there's no alert that happens.
Can someone please explain why nothing is alerted when I click the button and how I would make it work?
<html>
<body>
<a id="myButton" href="#">CLICK</a>
<script>
var myButton = document.getElementById("myButton");
var testingVar;
myButton.addEventListener("click", function() {
testingVar = "hello";
}, false);
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
</script>
</body>
</html>
Thanks.
Upvotes: 0
Views: 1352
Reputation: 27823
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 === undefined
function foo(){
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 fired
switch(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 executed
EVENT!
/* 5 seconds have passed, the function in setTimeout is executed */
Checking myvar
true
Upvotes: 3
Reputation: 8054
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
.
Upvotes: 0
Reputation: 2988
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.
Upvotes: 2