How to play a notification sound on websites?

There are various ways to play a notification sound on a website. IN this article we will play the notification sound in three different ways:
- Using Onclick Event in JavaScript
- Using Audio class in Javascript
- Using pure Jquery:
Below all the procedures are explained in details with the exxampl code:
- Using Onclick Event in Javascript: The onclick event fires the function when the user clicks on the button. In the following code, the play1 function is associated with onclick event. Function play1 receives the name of the audio file, then we select division with id=sound and inserts an HTML containing the audio tag.
Example:
<!DOCTYPE html><html><head><title>Notification Sound</title><style>body {text-align: center;}h1 {color: green;}</style><script>function play1() {/* Audio link for notification */var mp3 = '<sourcesrc=" "type="audio/mpeg">';document.getElementById("sound").innerHTML ='<audioautoplay="autoplay">' + mp3 + "</audio>";}</script></head><body><h1>zambiatek</h1><b>Notification Sound</b><br><!-- The onclick fires play1 function --><buttononclick="play1();">Get notification sound</button><divid="sound"></div></body></html> - Using Audio class in JavaScript: This method purely uses JavaScript where an Audio object is created and the in-built audio.play() method.
<!DOCTYPE html><html><head><title>Notification Sound</title><style>body {text-align: center;}h1 {color: green;}</style><script>function play2() {/* Audio link for notification */var audio = new Audio(" ");audio.play();}</script></head><body><h1>zambiatek</h1><b>Notification Sound</b><br><!-- Plays default sound that isalready set in the function --><buttononclick="play2();">Get notification sound</button></body></html> - Using pure Jquery: In this procedure, we Select play id and bind with click event. In the function, we create a new audio file and then play it.
<!DOCTYPE html><html><head><title>Notification Sound</title><style>body {text-align: center;}h1 {color: green;}</style><script>$(document).ready(function () {$("#play").click(function () {/* Audio link for notification */var audio = new Audio(" ");audio.play();});});</script></head><body><scriptsrc=</script><h1>zambiatek</h1><b>Notification Sound</b><br><buttonid="play">Get notification sound</button></body></html> - Output: For any procedure you use, it will work the same.



