I'm struggling to spot the error in my javascript code in pset8. Specifically the code doesn't execute as I'd expect when using an if statement within an event listener.
I've tried talking to the duck, but I still expect the button to change colour whenever clicked (from red to blue and vice versa) and the jpeg to appear and disappear, but unfortunately nothing happens at all.
The javascript is written below. The html above it includes a button with ID "myBtn" that starts as red, and a photo with ID "rick" (sorry!) that starts with style.visibility == 'hidden' (from my css style sheet).
<script>
var btn = document.getElementById("myBtn");
btn.addEventListener("click", function(){
if (btn.style.backgroundColor == 'red'){
btn.style.backgroundColor = 'blue';
btn.innerHTML = "Click to stop RickRoll";
} else if (btn.style.backgroundColor == 'blue'){
btn.style.backgroundColor = 'red';
btn.innerHTML = "Innocent-looking red button";
}
});
btn.addEventListener("click", rickroll);
var rick = document.getElementById("rick");
function rickroll(){
if (rick.style.visibility == 'hidden'){
rick.style.visibility = 'visible';
} else if rick.style.visibility == 'visible'){
rick.style.visibility = 'hidden';
}
}
</script>
If I simplify my code to remove the conditional statements, it behaves as expected but I would like to add the conditionals back in to make the page more dynamic.
Simplified code:
<script>
var btn = document.getElementById("myBtn");
btn.addEventListener("click", function(){
btn.style.backgroundColor = 'blue';
btn.innerHTML = "Click to stop RickRoll";
});
btn.addEventListener("click", rickroll);
var rick = document.getElementById("rick");
function rickroll(){
rick.style.visibility = 'visible';
}
</script>
Thanks in advance!