Search code examples
javascripthtmltypescripthtml5-videohtml5-audio

How to bing click/mousedown events for HTML Audio element


In the below shared stackblitz example, i have bound mousedown and click event for the audio element wrapper which is not triggered. I need to perform my own action, with audio element click being performed.

Couldn't find any solutions for this case, any thoughts over this is appreciated.

<span id="test">
<audio controls>
  <source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<br>
</span>
<script>
document.querySelector('#test').addEventListener('click', function() { console.log ('click called')});
document.querySelector('#test').addEventListener('mousedown', function() { console.log ('mousedown called')});

Sample: https://stackblitz.com/edit/9gw8e5-qujbbj?file=index.html,index.js

Any suggestions on this, to achieve this behavior. Couldn't find any suggestions regarding this in the MDN too (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio).


Solution

  • Tried the below way of wrapping inside the figure HTML element, which is an alternate solution instead of wrapping a separate element above the audio element. Those who want to wrap the audio elements within a inline/block nodes.

    ```css
    figure {
        display: block;
        outline: none;
        position: relative;
        margin: 0;
        padding: 0;
    }
    
    figure:after {
        position: absolute;
        content: "";
        z-index: 1;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        cursor: default;
        display: block;
        background: transparent;
    }
    
    ```html
    <span id="test">
      <audio controls>
        <source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
      Your browser does not support the audio element.
      </audio>
    </span>
    

    Sample: https://stackblitz.com/edit/9gw8e5-dswrh3?file=index.html,index.js

    Above sample makes the mousedown and click action work for the audio element.

    Hope it helps someone..!