Skip to content Skip to sidebar Skip to footer

Uncaught Typeerror: Cannot Read Property 'play' Of Null

Can anyone help me understand why I am getting this 'Uncaught TypeError: Cannot read property 'play' of null' error in my console? I am using google chrome if that helps at all. Th

Solution 1:

There should be no spacing in the selector portion or the desired element will not be found. You also did not use the right type of quotes for the ES6 reference you made; thus, ${e.keyCode} becomes processed as a string instead of a variable. You will want to use ` instead of " in this situation.

Current format:

const audio = document.querySelector("audio[data-key = '${e.keyCode}']");

Resolved format:

const audio = document.querySelector(\`audio[data-key="${e.keyCode}"]\`);

Solution 2:

Probably a better approach [this approach will work on Firefox and IE9+] you'll need to check with chrome for [event].key support.

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>JS Drum Kit</title><linkrel="stylesheet"href="Drum_Kit.css"></head><body><divclass="keys"><divdata-key="65"class="key"><kbd>A</kbd><spanclass="sound">clap</span></div><divdata-key="83"class="key"><kbd>S</kbd><spanclass="sound">hihat</span></div><divdata-key="68"class="key"><kbd>D</kbd><spanclass="sound">kick</span></div><divdata-key="70"class="key"><kbd>F</kbd><spanclass="sound">openhat</span></div><divdata-key="71"class="key"><kbd>G</kbd><spanclass="sound">boom</span></div><divdata-key="72"class="key"><kbd>H</kbd><spanclass="sound">ride</span></div><divdata-key="74"class="key"><kbd>J</kbd><spanclass="sound">snare</span></div><divdata-key="75"class="key"><kbd>K</kbd><spanclass="sound">tom</span></div><divdata-key="76"class="key"><kbd>L</kbd><spanclass="sound">tink</span></div></div><audioid=asrc="Crash-Cymbal-1.wav"></audio><audioid=ssrc="holy_hole.wav"></audio><audioid=dsrc="holy_heart_failure.wav"></audio><audioid=fsrc="holy_fruit_salad.wav"></audio><audioid=gsrc="holy_mashed_potatoes.wav"></audio><audioid=hsrc="holy_nightmare.wav"></audio><audioid=jsrc="holy_las_vegas.wav"></audio><audioid=ksrc="holy_caffeine.wav"></audio><audioid=lsrc="holy_alphabet.wav"></audio><script>window.addEventListener('keydown', function(e){
        this[e.key] ? this[e.key].play() : 0;
    });

    </script></body></html>

Post a Comment for "Uncaught Typeerror: Cannot Read Property 'play' Of Null"