I am trying to play sounds when my mouse rolls over images. I want to implement sound into this code. When the mouse rolls over the image, it not only change and displays a copy of the 2nd image, but it also plays a sound. Whats the best way to implement sound?

<script type="text/javascript">
          function swapImg(imgObj, isHover, imgOrg, imgHover) {
          imgObj.src = 'http://mysite/c_images/' + (isHover ? imgHover : imgOrg);
            var cloneImg = document.getElementById('b2');
            if(isHover) {
               cloneImg.src = 'http://mysite/c_images/' + imgHover;
               cloneImg.style.display = 'block';
               cloneImg.style.display = 'none';
<div id="b1">
<img src="http://mysite/c_images/b1.png" 
  alt="image and sound" 
  onmouseover="swapImg(this, true, 'b1.png', 'b.png');" 
  onmouseout="swapImg(this, false, 'b1.png', 'b1.png');"
<img id="b2" style="display: none;" />

thanks jb

  • I don't want to sound rude, but please stop asking the same question twice (http://doctype.com/apply-sounds-onmouseover-images) Mottie over 9 years ago

1 answer

Jordan 469

This script will add sound effects to onclick and onmouseover attributes of elements. Be sure to test them in different browsers, as not all Web browsers handle onmouseover and onclick attributes on elements other than links. Use JavaScript to Add Sound

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

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

The Sound is Placed in an Empty Span

The JavaScript places an embed tag inside an empty span tag when the script is initiated. So, you need to add the following span file somewhere within the body of your HTML page, preferably near the top of the document:

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

Call the Script with an onmouseover or onclick 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 those attributes: <p onmouseover="playSound('URL to soundfile');">&nbsp;</p>

Answered over 9 years ago by Jordan
  • Thanks, however, I don't understand the foward slashes. Is the code right? Battle Tested over 9 years ago
  • back slashes "\" you mean? It's to 'escape' the subsequent character. In this case, it is to escape the subsequent double quote character so that it doesn't conflict with the opening double quote for the string and close it. This will work too, ` src='"+soundfile+"' hidden='true' autostart='true' loop='false' `. o.k.w over 9 years ago