Alternative way to undo an addEventListener without removeEventListener?

Viewed 16

I just got started with JS and having hard time to deal with eventListeners...

I am trying to find a way to re-hide some HTML elements on my page after the user re-clicks on them again.

So far, the only way that I know to undo an Event which was triggered by using addEventListener is by assigning the same function to the same event (function removeEventListener), however, in the code below,it does not matter whether I try to use an anonymous function or if I reuse the same function and only change the "block" attribute back to "none"; It won't work.

Any suggestions ?

Thank you in advance.

let snake = document.getElementById("snake");
let space = document.getElementById("space");
let fortune = document.getElementById("fortune");

//elements to be changed

let figure1 = document.getElementById("figure1");
let figure2 = document.getElementById("figure2");
let figure3 = document.getElementById("figure3");


//functions

function addFigure1(){
    figure1.style.display="block";
 };

 function addFigure2(){
    figure2.style.display="block";
 };

 function addFigure3(){
    figure3.style.display="block";
 };



 ///////////////////////////////////////////////////////

snake.addEventListener("click",addFigure1);

space.addEventListener("click",addFigure2);

fortune.addEventListener("click",addFigure3);
1 Answers

You can set an attribute on the element which is the target of the event, thus saving the "state" of it

function addFigure1(){
    var display = figure1.getAttribute("display") || "block";
    figure1.style.display=display;
    display = display == "block" ? "none" : "block";
    figure1.setAttribute("display", display);
 };
Related