How to Play a Sound on Click or Rollover

Use dynamic HTML to play sounds

Loudspeaker in sky

Monty Rakusen / Getty Images

By 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

Create a script that adds sound effects when a customer clicks something using the attribute and when a customer rolls over something using the attribute. Test these effects 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\" />";
}
</script>

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

Add an element 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>
<html>
<head>
<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) {
  document.getElementById("dummy").innerHTML=
    "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
</script>
</head>
<body>
<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>
</body>
</html>
Format
mla apa chicago
Your Citation
Kyrnin, Jennifer. "How to Play a Sound on Click or Rollover." ThoughtCo, Sep. 30, 2021, thoughtco.com/play-sound-on-click-or-rollover-3469484. Kyrnin, Jennifer. (2021, September 30). How to Play a Sound on Click or Rollover. Retrieved from https://www.thoughtco.com/play-sound-on-click-or-rollover-3469484 Kyrnin, Jennifer. "How to Play a Sound on Click or Rollover." ThoughtCo. https://www.thoughtco.com/play-sound-on-click-or-rollover-3469484 (accessed April 19, 2024).