currently i am working on a wordpress site that provides the user with elements that can be faded in or out. in particular it is a soundbutton which is shown or hidden.
for the click function i have written a basic function that can be applied to multiple elements.
const soundButtonMobile = document.querySelector('.mobile-sound');
const soundButtonDs = document.querySelector('.desktop-sound');
function playSound(elem){
let isPlaying = false;
elem.addEventListener('click', () => {
if(!isPlaying){
elem.classList.add('sound-on');
isPlaying = true;
}
else{
elem.classList.remove('sound-on');
isPlaying = false;
}
console.log('clicked');
});
}
if( typeof soundButtonDs !== undefined || typeof soundButtonDs !== null ) playSound(soundButtonDs);
if( typeof soundButtonMobile !== undefined || typeof soundButtonMobile !== null ) playSound(soundButtonMobile);
if the button does not exist on the page then the functions parameter (elem) causes an error: Uncaught TypeError: elem is null
what is the better approach to deal with such errors since it is also a basic vanila js - no onload functions etc, the .js file looks like u see above.
any help or further understanding to deal with good development helps ... thank u m.
i tried to encapsulate the js function - not sure if it is the right term
$(function() { /* here i added the code from above */ }
window.onload=function() { /* here i added the code from above */ }
$(document).ready(function() { /* here i added the code from above */ });