I’m adding a listener for a Media API event as follows:
function addPlayListener() {
var video = document.getElementById("theVideo");
video.addEventListener('play', function() {alert('play');}, false); // method a
video.addEventListener('play', alert('play'), false); // method b
}
window.addEventListener('load', addPlayListener, false);
<video id="theVideo" controls width="180" height="160" src="sample_mpeg4.mp4"> </video>
Using method a everything works as expected, however using method b the alert is displayed as soon as the page loads (and doesn’t display when the event fires).
Why is this, is there something wrong with the syntax for method b?
According to addEvenListener documentation:
listenermust be:EventListenerinterface,alert()function does not return any object, which implementsEventListenerinterface, nor Javascriptfunction. Simply,alertdoes not return anything. So, what you get is: