Milan Panin
Milan Panin

Reputation: 95

How to exit from function and addEventListener? return not working?

let textList = document.getElementsByClassName('click');

let testFun = () => {
  for (let element of textList) {
    element.addEventListener('click', e => {
      console.log(e.target.textContent);

      if (e.target.textContent === 'TEXT3') {
        console.log('WIN!');
        return; // After this line I want the function to stop, but it still works. Why? And how to stop it?
      }
    });
  }
};

testFun();
<div>
  <p class="click">TEXT1</p>
  <p class="click">TEXT2</p>
  <p class="click">TEXT3</p>
  <p class="click">TEXT4</p>
</div>

It is clear to me that this is the basics of JavaScript, but I have not come to a solution for hours.

The application I am writing is based on the manipulation of DOM elements. I need a listener for several elements at the same time and for a hit on the right element, I want the function to stop working.

Also, the break keyword doesn't work either because I'm in a function inside addEventListener. So how do I solve this problem? Is there a mistake in the logic of the program?

Upvotes: 1

Views: 2152

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075527

return is returning from the event handler. No code in the event handler will run until after the testFun call has finished, if and when the click event occurs in one of the elements. Since testFun has already finished its work, there's nothing the code in the event handler can do to prevent that — it can't go back in time. :-)

You could remove the event handler from the elements (or just some of them?), though, so that they don't respond to clicks after the first click:

let testFun = () => {
    // Create the handler once
    const handler = e => {
        console.log(e.target.textContent);
  
        if (e.target.textContent === "TEXT3") {
            console.log("WIN!");
            // Remove it from the elements
            for (let element of textList) {
                element.removeEventListener("click", handler);
            }
        }
    };
    for (let element of textList) {
        element.addEventListener("click", handler);
    }
};

Upvotes: 3

Related Questions