📜  jquery Audio Play on button click - Javascript(1)

📅  最后修改于: 2023-12-03 14:43:08.428000             🧑  作者: Mango

jquery Audio Play on button click - Javascript

In this tutorial, we will learn how to create a simple audio player using jQuery and HTML5, and play the audio on a button click event.

Prerequisites
  • Basic knowledge of HTML5 and JavaScript.
  • Text editor of your choice.
Step 1: HTML Markup

In our HTML markup, we need to create a container div for the audio player, an audio element to load the audio file and a button element to play the audio on click.

<html>
<head>
	<title>jQuery Audio Play on button click - Javascript</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
	<div id="audio-container">
		<audio id="my-audio">
			<source src="audio_file.mp3">
		</audio>
		<button id="play-btn">Play</button>
	</div>
</body>
</html>
Step 2: jQuery Code

We will use jQuery to handle the button click event and play the audio.

$(document).ready(function(){
    $('#play-btn').on('click', function(){
        $('#my-audio')[0].play();
    });
});

The code above binds a click event to the play button. When the button is clicked, the play() method is called on the first audio element in the document, which is the one we named my-audio.

Step 3: Styling

Our audio player is basic and needs some styling to look good.

#audio-container{
    width: 300px;
    margin: 0 auto;
}
#audio-container audio{
    width: 100%;
}
#play-btn{
    margin-top: 10px;
    display: block;
    border: none;
    background-color: #1abc9c;
    color: #fff;
    padding: 10px;
    cursor: pointer;
}

The code above sets the dimensions and styles of our container, audio element and play button.

Conclusion

We have learned how to create a simple audio player using jQuery and play the audio on a button click event. With some additional effort, you can add more functionality to the player such as pause, rewind, and skip buttons.

Happy coding!