Skip to content
Advertisement

Javascript – Eventlistener function not working, toggle opacity on click

In the box I want it to say Hi, but when you click on the div “hi” it will instead toggle the div with “bye” using opacity. My design is not actually with text but svg paths, so this was the best way to translate what I need help with, without having to much code in the snippet (as the svg is quite a lot of code). However, when I click on “hi” nothing happens. What can I change to fix this?

As I am not very experienced with javascript, I am asking you for help to make this function actually work.

const Fana = document.getElementById("Fana")

Fana.addEventListener("onclick", FanaFunction());

function FanaFunction() {
  if (clicked = true) {
    document.getElementById("Fana").style.opacity = "0";
    document.getElementById("Fana-H").style.opacity = "1";
  } else {
    document.getElementById("Fana").style.opacity = "1";
    document.getElementById("Fana-H").style.opacity = "0";
  } else if {
    document.getElementById("Fana").style.opacity = "1";
    document.getElementById("Fana-H").style.opacity = "0";
  }
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100vh;
  background-color: black;
  font-family: sans-serif;
  font-size: 2em;
  text-transform: capitalize;
}

.box-test {
  text-align: center;
  border: solid 3px red;
  width: 400px;
  background-color: white;
}

#Fana {
  opacity: 1;
  cursor: pointer;
}

#Fana-H {
  opacity: 0;
  cursor: pointer;
}
<div class="box-test">
  <div id="Fana">hi</div>
  <div id="Fana-H">bye</div>
</div>

Advertisement

Answer

else if must be use befor of else!!! and else if need to () and condation. when use if must == or === this if (clicked = true) is not true code.

I fixed your code:

const Fana = document.getElementById("Fana")
let clicked = true;
Fana.addEventListener("click", FanaFunction);

function FanaFunction() {
  if (clicked ) {
    document.getElementById("Fana").style.opacity = "0";
    document.getElementById("Fana-H").style.opacity = "1";
    clicked =false
  } else {
    document.getElementById("Fana").style.opacity = "1";
    document.getElementById("Fana-H").style.opacity = "0";
    clicked=true;
  } 
}
Advertisement