Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to handle HTML5 media events using jQuery?
To handle HTML5 media events using jQuery, you can use event handlers like the click() method along with HTML5 audio/video element methods. HTML5 provides various media events such as play, pause, ended, and timeupdate that can be controlled through jQuery.
Example
You can try to run the following code to learn how to handle HTML5 media events such as playing and stopping audio ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = $(".myPlayer").length; // Count total audio players
var z = 0; // Start at first audio player
$("#play-bt").click(function(){
$(".myPlayer")[z].play();
$(".message").text("Music started");
});
$("#stop-bt").click(function(){
$(".myPlayer")[z].pause();
$(".myPlayer")[z].currentTime = 0;
$(".message").text("Music Stopped");
});
});
</script>
</head>
<body>
<audio class="myPlayer" controls>
<source src="sample-audio.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<div class="message"></div>
<a id="play-bt" href="#">Play music</a><br>
<a id="stop-bt" href="#">Stop music</a><br>
</body>
</html>
In this example:
- The
play()method starts audio playback - The
pause()method pauses the audio - Setting
currentTime = 0resets the audio to the beginning - jQuery selectors are used to target the audio element and update the message display
Conclusion
jQuery provides an easy way to handle HTML5 media events by combining jQuery event handlers with native HTML5 audio/video methods. This approach gives you full control over media playback and user interaction.
Advertisements
