0

I have some Javascript (below) that is resulting in a console error: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener').

var trigger = document.getElementById("hello");
var audio = new Audio('audio/hello.mp3');

window.addEventListener('DOMContentLoaded', () => { 
    trigger.addEventListener("click", function(event) {
        event.preventDefault();
        audio.play();
    }, false);
});

I believe this is because all my script is in a single .js file and as the page I'm viewing doesn't run this script it can't find the element it's related to.

As the above script is only run on a certain template. I thought I could wrap it in the following but that didn't seem to work and threw up it's own errors?

if (document.querySelector('.template-name') { // Existing Code }

Not sure if there's more of a 'global' way to prevent these types of error but I thought just checking the html element had a certain class seemed like a good workaround for this instance?

user1406440
  • 1,329
  • 2
  • 24
  • 59
  • Probably because DOM is not yet loaded, move `var trigger...` as the first line in `DOMContentLoaded` handler. – Jan Pfeifer Jan 23 '23 at 12:23
  • What about putting trigger and audio inside the DOMContentLoaded function? – evolutionxbox Jan 23 '23 at 12:24
  • I actually just added that `DOMContentLoaded` as it prevented a JS Lint error. So happy to remove that. Would the `if` replace that first line? – user1406440 Jan 23 '23 at 12:25
  • Don't remove the `DOMContentLoaded`. It's likely the solution to your issue. Consider reading up on why it's used? – evolutionxbox Jan 23 '23 at 12:26
  • Look at : https://www.javascripttutorial.net/javascript-dom/javascript-domcontentloaded/ – Jan Pfeifer Jan 23 '23 at 12:27
  • 2
    If your `#hello` element doesn't exist on the current page, then `trigger` will of course be `null`. So simply check, before you try to call addEventListener on it - `if(trigger) { trigger.addventListener(...); }` – CBroe Jan 23 '23 at 12:31
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – evolutionxbox Jan 23 '23 at 12:32
  • @CBroe thanks, wrapping `if(trigger) { }` around the script works. It could even go around the `window.addEventListener('DOMContentLoaded', () => { ` and work as well. Why does that work but the `querySelector` with class not work? – user1406440 Jan 23 '23 at 12:34
  • Have you tried moving your event listener to the top of the script? – Bernard Borg Jan 23 '23 at 12:35
  • 1
    `if (document.querySelector('.template-name') { // Existing Code }` will "throw up it's own errors" simply because there is a `)` missing. – CBroe Jan 23 '23 at 12:39
  • That that's more a typo on my behalf posting this. Happy to mark your answer so all good now! :) – user1406440 Jan 23 '23 at 12:50

0 Answers0