How to Create a Play/Pause Toggle Button with jQuery?

Estimated read time 3 min read

Here’s an example of how to create a Play/Pause toggle button with jQuery:

HTML code:

<!DOCTYPE html>
<html>
<head>
	<title>Play/Pause Toggle Button with jQuery</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<style>
		#player {
			width:400px;
			height:200px;
			background-color:#eee;
			position:relative;
		}
		
		#player video {
			position:absolute;
			top:0;
			left:0;
			width:100%;
			height:100%;
			display:none;
		}
		
		#player.playing video {
			display:block;
		}
		
		#player button {
			position:absolute;
			top:50%;
			left:50%;
			transform:translate(-50%, -50%);
			border:none;
			background-color:transparent;
			cursor:pointer;
			font-size:30px;
			display:none;
		}
		
		#player.playing button.pause {
			display:block;
		}
		
		#player:not(.playing) button.play {
			display:block;
		}
	</style>
</head>
<body>
	<div id="player">
		<video src="video.mp4"></video>
		<button class="play"></button>
		<button class="pause">❚❚</button>
	</div>
	
	<script>
		$(document).ready(function(){
			var player = $("#player");
			var video = player.find("video")[0];
			var playButton = player.find(".play");
			var pauseButton = player.find(".pause");
			
			playButton.click(function(){
				player.addClass("playing");
				video.play();
			});
			
			pauseButton.click(function(){
				player.removeClass("playing");
				video.pause();
			});
		});
	</script>
</body>
</html>

In this example, we have a div element with the ID “player” that contains a video element and two button elements: one with the class “play” and one with the class “pause”.

We also have a script tag where we add our jQuery code. In the script, we define variables for the player, video, playButton, and pauseButton elements using the $() syntax.

We then use the click() method to listen for clicks on the playButton. When the button is clicked, we add the “playing” class to the player element using the addClass() method, and call the play() method on the video element.

We also use the click() method to listen for clicks on the pauseButton. When the button is clicked, we remove the “playing” class from the player element using the removeClass() method, and call the pause() method on the video element.

We use CSS to show and hide the appropriate elements based on the state of the player element. When the player element has the “playing” class, we show the video element and the “pause” button, and hide the “play” button. When the player element does not have the “playing” class, we do the opposite.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply