onvolumechange

The onvolumechange event in HTML is triggered when the volume of audio or video content is adjusted, allowing scripts to react to these changes in volume.

onvolumechange event

The onvolumechange event attribute triggers a script whenever the volume of a media element (<audio> or <video>) is altered. It's helpful for updating the UI or giving feedback based on volume changes.

Syntax

In HTML

index.html
<element onvolumechange ="myScript">

In JS

script.js
object.onvolumechange  = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("volumechange ", myScript);

Example

::event-onvolumechange ::
index.html
<!DOCTYPE html> 
<html> 
<body> 
<h1>HTML DOM Events</h1>
<h2>The onvolumechange Event</h2>

<p>Assign an "onvolumechange" event to a video element:</p>

<video controls onvolumechange="myFunction()">
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<p>Video courtesy of <a href="https://institute.qarpeo.com" target="_blank">Tree</a>.</p>

<p>Try to change the volume.</p>

<p id="demo"></p>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML += "The volume has been changed! ";
}
</script>

</body> 
</html>

Values

  • <script>
    • Specifies the <script> to run when the volume change event is triggered.

Conclusion

The onvolumechange event is triggered when the volume of a media element is adjusted. It allows developers to run scripts in response to volume changes, such as updating the UI or providing feedback. This enhances user interactivity and control over media playback.