0

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 */ });
mashup
  • 1
  • 1
    Linked dupe explains all the ways. If the buttons do not exist than a simple truthy check is all you need. `if (soundButtonMobile) playSound(soundButtonMobile);` – epascarello May 10 '23 at 13:26
  • thank u, it helped to understand the problem i was looking for! – mashup May 10 '23 at 18:20

0 Answers0