Explain Codes LogoExplain Codes Logo

Play/pause HTML 5 video using jQuery

html
responsive-design
video-controls
event-handling
Anton ShumikhinbyAnton Shumikhin·Dec 20, 2024
TLDR

Effortlessly toggle video play state with jQuery:

$('#toggle').click(() => $('#video')[0].paused ? $('#video')[0].play() : $('#video')[0].pause());

Ensure #video is your video's ID and #toggle is the button's ID. With this nugget of code, if the video is paused, we play it, else we hit the pause button.

Finessing video controls with jQuery

Despite jQuery's nifty features, plain JavaScript could suffice. Yet, video control is ideal with jQuery, when it coexists with intricate DOM manipulations and complex event handling.

When to unaShamedly choose jQuery

Leverage jQuery for video control, especially in a narrow corridor of DOM manipulations or for staff-wide familiarity and convenience.

If jQuery already nests in your Dom

Imagine, your code depends heavily on jQuery, it's prudent to stick to jQuery for consistency and code compactness:

$('.videoClass').click(function() { var video = $(this).get(0); // Are we there yet? video.paused ? video.play() : video.pause(); });

This snippet conveniently toggles play/pause on video click.

Freeze all when you roam around

In picture perfect scenarios, like tabbed content or carousel displays, with videos not in view, jQuery ensures they all rest:

$('a.tab').on('click', function() { $('video').each(function() { // Rest, sweet prince this.pause(); }); });

This snippet ensures your users won't be startled by unseen videos playing in the background.

The trait of your ultra-responsive video

Let's have a gallery walk through some invaluable best practices that account for an ultra-responsive HTML5 video.

No assumption. Check.paused then toggle

Before play or pause, we ensure to check if the video is at rest or not, saving us unwanted play/pause calls:

$('#playPauseButton').click(function() { var videoElement = $('#myVideo').get(0); // Knock knock. Who's there? videoElement.paused ? videoElement.play() : videoElement.pause(); });

Delegate, believe in the DOM

Event delegation is your winning ticket when your DOM sees dynamically loaded content:

$(document).on('click', '.playPause', function() { var videoElement = $(this).siblings('video').get(0); // Stop! Hammertime! videoElement.paused ? videoElement.play() : videoElement.pause(); });

This tiny whiz-kid responds even to newbie .playPause buttons introduced post initial page load.

JavaScript - Aye Aye Captain!

For single video element manipulation, pure JavaScript could be your pal:

document.getElementById('playPause').addEventListener('click', function() { var videoElement = document.getElementById('myVideo'); // Shall we dance? videoElement.paused ? videoElement.play() : videoElement.pause(); });

JavaScript, being leaner, is much faster and efficient for the ones not fascinated by jQuery.