skip to Main Content

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


  1. You are trying to add undefined as a click listener, returned from appear/disappear function.

    You should pass a function instead.

    hello.addEventListener('click', () => {
      disappear(hello);
    });
    
    Login or Signup to reply.
  2. 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:

    function disappear(variable) {
       return () => variable.style.display = 'none';
    }
    function appear(variable) {
       return () => variable.style.display = 'block';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search