'Click event doesn't fire on an audio element in chrome
I have an audio element in my DOM. I executed the following command and it seems like the click event does not fire for some reason:
$0.addEventListener('click',function(){console.log('click')});
When i tried adding a mouseover handler it worked as expected:
$0.addEventListener('mouseover',function(){console.log('mouseover')});
In Firefox the click event works properly. Any ideas?
Solution 1:[1]
"If the user agent exposes a user interface to the user by displaying controls over the media element, then the user agent should suppress any user interaction events while the user agent is interacting with this interface. (For example, if the user clicks on a video's playback control, mousedown events and so forth would not simultaneously be fired at elements on the page.)" — from The Web Hypertext Application Technology Working Group
It's intended not to work, so "malicious" websites can't capture users' clicks on media controls. So it's not advisable to get around it in general cases; but if you really have to, you have to follow some hack like programmatically wrapping the audio element in a transparent element with a higher z-index (be careful with z-indices and transparency) and capturing the clicks for the said element.
Solution 2:[2]
Directly, it wont work.
You will need to add a shimified div aroudn it to get the click event.
Javascript:
function onAudioElClick() {
console.log('click');
}
HTML:
<div onclick="onAudioElClick()" style="position:absolute; z-index:9999; width:300px; height:30px;"></div>
<audio></audio>`
Solution 3:[3]
It's very strange that mouseover works but click not.
If you will wrap audio element inside to other element like div then you can handle click event:
JavaScript:
<div>
audio element
<audio src="http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg" autoplay></audio>
</div>
HTML:
var el = document.querySelector("div");
el.addEventListener('click',function(){console.log('click')});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Salim Mahboubi |
| Solution 2 | Herman L |
| Solution 3 | Arkadiusz Wieczorek |
