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?