1

I added an addEventListener to my window, but it is returning the following errors:

Uncaught TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only 1 present. at

window.addEventListener('DOMContentLoaded', setUpStuff, false);

Another error:

Uncaught TypeError: Cannot read property 'addEventListener' of null (at:

 optionsButton.addEventListener('click', function() {

Here is the code:

window.addEventListener('DOMContentLoaded', setUpStuff, false);
function setUpStuff(){
    let optionsButton = document.getElementById('#go-to-options');
    optionsButton.addEventListener('click', function() {
        if (chrome.runtime.openOptionsPage) {
          chrome.runtime.openOptionsPage();
        } else {
          window.open(chrome.runtime.getURL('options.html'));
        }
      });
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Angelina Tsuboi
  • 196
  • 1
  • 2
  • 14
  • `optionsButton.addEventListener(function()` - you're missing the event type you want to listen to. `"click"` ? – blex Jun 19 '20 at 21:09
  • Does this answer your question? [Why does \`document.getElementById(“#datepicker1”)\` not find my element?](https://stackoverflow.com/questions/33036800/why-does-document-getelementbyid-datepicker1-not-find-my-element) – Sebastian Simon Jul 06 '20 at 04:55
  • Related: [When to use the `#` symbol to get a DOM element?](https://stackoverflow.com/q/15486154/4642212). – Sebastian Simon Jul 06 '20 at 04:55

1 Answers1

2

You are supposed to add an event on the execution of which the function is going to be run. And getElementById takes an ID, not a selector, so you need to remove the #:

window.addEventListener('DOMContentLoaded', setUpStuff, false);
function setUpStuff(){
    let optionsButton = document.getElementById('go-to-options');
    optionsButton.addEventListener('click', function() {
        if (chrome.runtime.openOptionsPage) {
          chrome.runtime.openOptionsPage();
        } else {
          window.open(chrome.runtime.getURL('options.html'));
        }
      });
}
blex
  • 24,941
  • 5
  • 39
  • 72
Talmacel Marian Silviu
  • 1,596
  • 2
  • 6
  • 14
  • I added your code, but I am getting another error: Uncaught TypeError: Cannot read property 'addEventListener' of null on "optionsButton.addEventListener('click', function() {" – Angelina Tsuboi Jun 19 '20 at 21:14
  • remove the id sign from this code let optionsButton = document.getElementById('#go-to-options'); Should be like this let optionsButton = document.getElementById('go-to-options'); You are already telling to select an id, you don't need the id sign. – Talmacel Marian Silviu Jun 19 '20 at 21:19
  • Awesome! I got the right answer. Thank you so much! – Angelina Tsuboi Jun 19 '20 at 21:21