Search code examples
javascriptdomgoogle-chrome-extensiondom-events

Adding Multiple Event Listeners in Chrome Extension


I'm trying to add event listeners to multiple elements with the same class on the chrome extension popup. The event listeners are triggered with 'click' and open a new tab. My popup.html file looks something like this

...
<li class="listing">List1</li>
<li class="listing">List2</li>
...
<scripts src="popup.js"></script>
...

Whenever the list tags are clicked, they should open a new tab, but this never happens. Here is what my popup.js file looks like

function openLink(end){
    const term = end.trim().split(" ").join("+");
    chrome.tabs.create({url:`https://google.com/search?q=${term}`});
}

var inputs = document.getElementsByClassName('listing');
for( var i=0; i<inputs.length; i++){
   document.addEventListener("DOMContentLoaded",function(){
      inputs[i].addEventListener("click", function() { openLink("meep") } );
   })
}

The openLink function should work fine, it's just the event listeners. I have also tried leaving the "DOMContentLoaded" event listener outside the for loop but nothing happened. Any fixes?


Solution

  • Problem was fixed. Rather than adding an event listener, I had to add the .onclick event on the creation of the element.