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">
<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">
(function() {
  var c = document.getElementById("audio");
  c.addEventListener("click", play(), false);

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 () {

// Or:

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


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.