I have a single page app (SPA) with search functionality where I am trying to track how users interact with the search bar in Adobe Analytics. If I navigate to 5 different "pages" of my SPA, the following code will fire the event 6 times. Seems the addEventListener
is being set but not cleared if no search happens on a "page". These eventListeners essentially get queued each time a "page" loads, and once a search is entered, they all fire at the same time, clearing the queue.
How can I clear the eventListeners if a search is NOT performed and only have this event fire once a search is performed via pressing enter?
Suppose I have the code:
clearInterval(interval);
var interval = setInterval(function(){
if (document.querySelector("form div[data-autoid='search_bar'] input")) {
inputField = document.querySelector("form div[data-autoid='search_bar'] input")
inputField.addEventListener('keydown', searchEntered)
clearInterval(interval);
}
}, 500);
function searchEntered(e) {
if (e.key == "Enter") {
console.log("search entered");
var event = new CustomEvent('searchEntered');
dispatchEvent(event);
}
}