how to add addEventListener to generic js file loaded by files not containing object listened

Viewed 24

I have a js file with multiple functions around a single domain. This file is used by multiple php files. In the js I have 2 addEventListener for 2 forms, but both forms are in different php files. Now if I am loading the file that does NOT have <form id="quote">, the js

  const formQuote = document.querySelector('#quote');
  formQuote.addEventListener('submit', (event) => {

wants to create an addEventListener on a NULL object. How do I prevent this (sorry, new to php, js, etc).

1 Answers

You can just check if the element is null or not using an if statement. Value null is a falsy value, which means in if statement it evaluates to false. You can read more about falsy values in JavaScript here: https://www.freecodecamp.org/news/falsy-values-in-javascript/

const formQuote = document.querySelector('#quote');

if (formQuote) {
  formQuote.addEventListener('submit', (event) => {
    console.log('test')
  })
}

Related