How to Play a Sound on Click or Rollover

Use Dynamic HTML to play sounds

Loudspeaker in sky

 Monty Rakusen / Getty Images

One of the features of computer applications is that there is feedback when you do something. The most common type of feedback is sound. The computer clicks when you select things, beeps when there are errors, and makes other noises to alert you to situations. But web pages don't have this type of feedback. This makes them seem dull or non-responsive.

Luckily it's easy to change that. Using dynamic HTML attributes and sounds, you can create a web page that acts more like an application.

Add Sound When a Customer Clicks Something

This script will add sound effects when a customer clicks on something using the attribute and when a customer rolls over something using the attribute. Be sure to test them in different browsers, as not all web browsers handle on mouseover and on click attributes on elements other than links.

Place the following script in the HEAD of your HTML document:

<script language="javascript" type="text/javascript">
function playSound(soundfile) {
document.getElementById("dummy").innerHTML= "<embed src=\""
+soundfile+"\" hidden=\"true\" autostart=\"true\"
loop=\"false\" />";

Place Sound in an Empty Span

The JavaScript places an EMBED element inside an empty SPAN element when the script is initiated. So, you need to add the following SPAN tag somewhere within the BODY of your HTML page, preferably near the top of the document:

<span id="dummy"></span>

Call the Script With an Attribute

The last thing you need to add is an element that you want to generate the sound on click or on mouseover. Call the script with one of these attributes. Replace UrlToSoundFile with the full URL to the sound file you'd like it to play:

<a href="#" onclick="playSound('UrlToSoundFile');">Click here to hear a sound</a>
<p onmouseover="playSound('UrlToSoundFile');">Mouse over this text to hear a sound</p>

Here is the entire HTML document, playing the sound of a bluejay. The sound file is stored in the same directory as the HTML page:

<!doctype html>
<meta charset="ISO-8859-1" />
<title>Example of How to Play a Sound on Click or on MouseOver</title>
<script language="javascript" type="text/javascript">
function playSound(soundfile) {
    "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
<span id="dummy"></span>
<p><a href="#" onclick="playSound('zbluejay.wav');">Click here to hear a bird sing</a></p>
<p onmouseover="playSound('zbluejay.wav');">Or you can put your mouse over this paragraph to hear the same bird sound.</p>