Reputation: 41
Last question I'm asking. I'm trying yo get my audio to play when my classes toggle but I don't know what if else statement to use.
html:
<section id="sound">
<img id="speaker" src="img/mic.svg">
<section>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</section>
</section>
css:
#sound {
width: 3em;
height: 3em;
margin: 5em 1em;
position: absolute;
display: flex;
}
#sound div {
width: 0.3em;
background: black;
border: 1px solid white;
border-radius: 2em;
}
.one {
margin-top: 1em;
height: 1em;
transition:all 300ms ease-in-out;
}
.oneanimated {
height: 2em;
margin-top: 0.5em;
margin-left: 1em;
transform: rotate(-45deg);
transition:all 300ms ease-in-out;
}
javascript:
var backgroundtelegrafisch = document.getElementById("backgroundtelegrafisch");
var sound = document.getElementById("sound");
var one = document.getElementsByClassName("one");
var oneanimated = document.getElementsByClassName("one");
function animatie () {
one[0].classList.toggle("oneanimated");
two[0].classList.toggle("twoanimated");
three[0].classList.toggle("threeanimated");
if (one == oneanimated){
backgroundtelegrafisch.play();
} else {
backgroundtelegrafisch.pause();
console.log("test");
}
}
sound.addEventListener("click", animatie);
The console.log never appeared, so the else statement never occurs. How can I fix this?
Upvotes: 0
Views: 3034
Reputation: 3637
The reason you're not seeing anything in the console is because, well, the if
always succeeds. You do this:
var one = document.getElementsByClassName("one");
var oneanimated = document.getElementsByClassName("one");
...which means one
and oneanimated
are exactly the same as each other. You then do this:
if (one == oneanimated){
backgroundtelegrafisch.play();
} else {
backgroundtelegrafisch.pause();
console.log("test");
}
Can you see the problem now? You're comparing one
and oneanimated
, and since they're the same (as we saw earlier) the code will always hit the backgroundtelegrafisch.play();
line instead of going into the else
.
Instead of trying to compare one
to oneanimated
, you should instead do this:
if (one[0].classList.contains("oneanimated")){
backgroundtelegrafisch.play();
} else {
backgroundtelegrafisch.pause();
console.log("test");
}
The contains
method of classList
checks if the element has the specified class.
Upvotes: 1