How to Play a Sound on Click or Rollover

Use Dynamic HTML to Play Sounds

Sound to ear
Image courtesy artpartner-images / Getty

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 onmouseover and onclick attributes on elements other than links.

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

 

The Sound is Placed 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:

 

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:

onclick="playSound('UrlToSoundFile');">Click here to hear a sound

onmouseover="playSound('UrlToSoundFile');">Mouse over this text to hear a sound

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. The relevant portions are highlighted:

 





Example of How to Play a Sound on Click or on MouseOver


 

 

 

onclick="playSound('zbluejay.wav');">Click here to hear a bird sing

 

 

 

 

onmouseover="playSound('zbluejay.wav');">Or you can put your mouse over this paragraph to hear the same bird sound.

 

 

 

 

 

 

Format
mla apa chicago
Your Citation
Kyrnin, Jennifer. "How to Play a Sound on Click or Rollover." ThoughtCo, Jun. 15, 2017, thoughtco.com/play-sound-on-click-or-rollover-3469484. Kyrnin, Jennifer. (2017, June 15). 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 October 18, 2017).