The HTML onvolumechange attribute is an event handler used to specify a script that will run when the volume of a media element (audio or video) changes.
Definition and Usage
➔ This event can be triggered by the user or programmatically when the volume is increased, decreased, muted, or unmuted.
➔ The onvolumechange event attribute is used with audio and video tags.
Syntax
//In HTML
<video controls onvolumechange="myFunction()" id="sample">
<source src="video-source.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
//In javascript
document.getElementById("sample").onvolumechange=function() {myFunction();};
//OR
document.getElementById("sample").addEventListener("volumechange", myFunction);
//OR
document.getElementById("sample").addEventListener("volumechange", (event) => {
myFunction();
});
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| onvolumechange | <audio>, <video> |
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML onvolumechange attribute example</title>
</head>
<body>
<h3>HTML onvolumechange attribute example</h3>
<p>onvolumechange event fires whenever the volume of a media element (audio or video) is changed.</p>
<p id="output">Playing position:</p>
<!-- "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4" -->
<video controls onvolumechange="volumeChange(event)" ontimeupdate="myFunction(event)" id="sample">
<source src="video-source-path.mp4" type="video/mp4">
This browser does not support the video tag.
</video>
<script>
//In javascript
//document.getElementById("sample").onvolumechange=function() {myFunction();};
//OR
//document.getElementById("sample").addEventListener("volumechange", myFunction);
function myFunction() {
var video = document.getElementById("sample");
var time = video.currentTime;
var soundStatus = "";
if (video.muted) {
soundStatus = "Muted"
} else (
soundStatus = "Unmuted"
)
document.getElementById("output").innerHTML = "Playing position: " + time.toFixed(2) + " and Volume: " + video.volume * 100 + "% " + " Sound Status: " + soundStatus;
}
function volumeChange() {
alert("The volume has been changed.");
}
</script>
</body>
</html>
Click on the "Try it Now" button to see how it works.