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

Time:10-21

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) => {
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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')
  })
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related