Adding event listener to audio HTML5 tag in javascript

30,269

Solution 1

try:

audio.addEventListener('ended', foo);

This is the correct and standard method to add event listeners.

Solution 2

First, make sure whether audio element has the event before you use it, suppose the HTMLAudioElement is audio, you can test it like this audio.hasOwnProperty('onended')

Based on my browser, it doesn't support.

Share:
30,269

Related videos on Youtube

Paolo
Author by

Paolo

Updated on July 09, 2022

Comments

  • Paolo
    Paolo almost 2 years

    Hi I'm creating a new audio tag element in Javascript this is the code:

    var audio = document.createElement("audio");
    audio.setAttribute("id","myid");
    audio.setAttribute("autoplay","autoplay");
    document.body.appendChild(audio);
    

    before appending it to the body, I'd like to place an onended event handler, I tried something like this:

    audio.onended = foo;
    

    where foo is something like: function foo(){alert('Hola')}

    and

    audio.setAttribute("onended","foo()");
    

    in both case it didn't work. In the first case the audio tag is appended without any onended event handler; while in the second case the audio tag is appended, the onended event is on the attributes but it does not fire.

    does someone have any idea?

    thanks in advance.

    -z-

  • KateYoak
    KateYoak almost 12 years
    Before I stumbled upon this answer, I tried, $(audio).bind('onended'). Not suprisingly, it did not work. Yours does, and so did $(audio).bind('ended'). Can't decide which I like better... in jquery-depended code.
  • Variant
    Variant almost 12 years
    In jQuery dependent code where all your bindings are made through jQuery there is no reason to make an exception when it comes to audio elements.
  • svidgen
    svidgen over 10 years
    Works. But I'm pretty sure it's inaccurate to say, "This is the correct and standard method to add event listeners." Directly assigning event listeners is still a supported mechanism for pretty much every other tag. That it doesn't work on the audio tag for this particular event is a bit of an anomaly.
  • Variant
    Variant over 10 years
    Directly assigning events (The traditional model) works for most events but certainly not for all and surely not for custom events. Also you can only assign one event handler and not append and remove multiple listeners. the standard (w3c) way is by using addEventListener. Read more here quirksmode.org/js/events_advanced.html