Trying to convert simple inline JS to EventListener

I am trying to convert the following to use an event listener:

<audio id="audio">
  <source src="audio/hello.mp3" type="audio/mpeg">
</audio>
<a href="#" onClick="document.getElementById('audio').play(); return false;"> Link </a>

My attempt gives an Uncaught ReferenceError.

<audio id="audio">
  <source src="audio/hello.mp3" type="audio/mpeg">
</audio>
<span>Link</span>
<script>
(function() {
  var c = document.getElementById("audio");
  c.addEventListener("click", play(), false);
}());
</script>

That’s because there is no function play(), it’s a method of the audio element; also you don’t want to pass the result of calling that method to the event listener (which would also have the audio play immediately), but a function to call it:

var startBtn = document.getElementById('start-btn')
var audio = document.getElementById('audio')

startBtn.addEventListener('click', function () {
  audio.play()
})

// Or:
startBtn.addEventListener('click', audio.play.bind(audio))

// Nicest: ES6
startBtn.addEventListener('click', () => audio.play())

3 Likes

Nice one! Thanks @m3g4p0p

3 for the price of 1! :slight_smile:

1 Like

np :-)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.