I am trying to make this phrase switch each time a mouse event occurs. I don’t really care which mouse event, I tried mouseover and others because I thought that would be cool. I am getting something wrong, but I have no idea what is wrong. I already have the tag.
const hello = document.getElementById("hello");
const ciao = document.getElementById("ciao");
const hola = document.getElementById("hola");
const bonjour = document.getElementById("bonjour");
function disappear(variable) {
variable.style.display = 'none';
};
function appear(variable) {
variable.style.display = 'block';
};
hello.addEventListener('click', disappear(hello));
ciao.addEventListener('click', appear(ciao));
ciao.addEventListener('click', disappear(ciao));
hola.addEventListener('click', appear(hola));
hola.addEventListener('click', disappear(hola));
bonjour.addEventListener('click', appear(bonjour));
bonjour.addEventListener('click', disappear(bonjour));
hello.addEventListener('click', appear(hello));
<div class="hello-world">
<button id="hello"> Hello, World! </button>
<button id="ciao"> Ciao, Mondo!</button>
<button id="hola"> Hola, Mundo!</button>
<button id="bonjour"> Bonjour le monde!</button>
</div>
2
Answers
You are trying to add
undefined
as a click listener, returned fromappear
/disappear
function.You should pass a function instead.
The answer from "het" is correct. You need to pass a function, not call it. However, you can also fix your code by having your appear/disappear functions return a callback, so there’s a bit more reusability: