3

Given the following markup:

<audio controls onclick="alert('hi')">
    <source src="/url/track.mp3" type="audio/mpeg">  
</audio>

I get no response from the onclick event. Seems like all the onclick events are bound to the player controls.

My goal is to run a separate function when the user hits "play".

2 Answers 2

9

The onplay attribute is what you're looking for.

<audio onplay="myFunction()">...</audio>

Here's some article on w3schools about it

Sign up to request clarification or add additional context in comments.

1 Comment

How can you tell if a human clicked Play or if Javascript triggered the playback via audio.play()
0

You can place an invisible div over the audio element:

<script>
    function catchClick(){
        alert("hi");
    }
</script>

<div onclick="catchClick()" style="position:absolute;z-index:1;width:300px;height:30px;">
</div>
<audio controls>
    <source src="/url/track.mp3" type="audio/mpeg">
</audio>

Then, in the catchClick function you can pass the mouse clicks to the audio element via this method How to simulate a mouse click using javascript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.