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();
}
EventTarget.addEventListener()
Parameters:
Options: Optional
once
: A Boolean indicating that the listener should be invoked at most once after being added. Iftrue
, 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" />
You can check whether it's already inserted.
if (newView.innerHTML.indexOf("Luke Skywalker") < 0) {
// code to insert
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With