Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire a function only once in JavaScript

I am building a Star Wars Search Application where I have an object full of Star Wars Character Information, You can dynamically search through the object using a map function that matches it to a Regular Expression that fires as the user is searching for a character.

That all works perfectly but I have added the functionality for the user to click on a character (e.g Luke Skywalker) this will then append HTML to the view and add information regarding Luke. I am struggling to get this function to only fire once, user can click multiple times on the character and it will keep on adding the same content.

How can I only allow the user to click on the <li> once so that the function displayInfo() will fire once.

Thanks for the help.

var newView = document.querySelector(".starwars");

function displayInfo() {

    newView.innerHTML += `
      <div class="jedi">
      <div class="image-wrapper">
          <img id="swImage"src="img"
              class="thumb reserved-ratio" alt="Luke Skywalker">
      </div>
      <div class="desc-sizer">
          <p class="desc">Luke Skywalker was a Tatooine farmboy who rose from humble beginnings to become one of the greatest Jedi the galaxy
              has ever known.
          </p>
      </div>
    </div>
      `;
    searchInput.value = 'Luke Skywalker';
    searchInput.addEventListener("focus", displayMatches);
    searchInput.focus();
}
like image 763
The Grey Wolf Avatar asked Jan 27 '23 23:01

The Grey Wolf


2 Answers

EventTarget.addEventListener() Parameters:

Options: Optional

once: A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

You can pass { once: true } to addEventListener() as the third parameter:

searchInput.addEventListener("focus", displayMatches, { once: true });

Demo:

function displayInfo() {
  var searchInput = document.querySelector('.searchInput');
  searchInput.value = 'Luke Skywalker';
  searchInput.addEventListener("focus", displayMatches, {once: true});
  searchInput.focus();
}
displayInfo();
function displayMatches(){
  alert('This function will be invoked only once!!!');
}
<input class="searchInput" />
like image 62
Mamun Avatar answered Jan 29 '23 13:01

Mamun


You can check whether it's already inserted.

if (newView.innerHTML.indexOf("Luke Skywalker") < 0) {
    // code to insert 

}
like image 33
Majid Laissi Avatar answered Jan 29 '23 12:01

Majid Laissi