-1

I have problem. When I want to run sound from image I got error

Uncaught TypeError: Cannot read property 'addEventListener' of null

My html code

<html>
<head>
<title>Music</title>
</head>
<body>
    <audio id="audio" src="http://www.soundboard.com/handler/DownLoadTrack.ashx?cliptitle=Never+Gonna+Give+You+Up-+Original&filename=mz/Mzg1ODMxNTIzMzg1ODM3_JzthsfvUY24.MP3"></audio>

    <script>
    document.getElementById('play').addEventListener('click', function (e) {
    e.preventDefault();
    document.getElementById('audio').play();
    });
    </script>

    <a href="#" id="play">
        <img src="test.png">
    </a>
</body>
<footer>
</footer>

2
  • 1
    Your JS code is above the element. The DOM has not loaded the element yet, so it is undefined. Either move your script below the element, or add it to an onload event handler so it runs after the DOM has fully loaded.
    – user47589
    Dec 6, 2019 at 21:51
  • Thank you! I'm gonna remember next time :)
    – DeJzer
    Dec 6, 2019 at 22:03

1 Answer 1

0

You should try to run your script after the document is fully loaded so that the tag with id : 'play' actually exists.

Something like this

window.onload=function(){
  ...
}

**P.S : ** Source for solution and alternate potential fixes : Cannot read property 'addEventListener' of null

Not the answer you're looking for? Browse other questions tagged or ask your own question.