Innnards: How do I play a sound only on the first mouseover?

As the author of the WWW FAQ, I regularly answer questions about the workings of the Web. If a question is frequently asked, I simply add an article to the FAQ. But sometimes a question is more detailed, more in-depth— not really a FAQ, but still of interest to others. You'll find those questions, with my answers, here in Innards along with commentary on other web-technology-related topics.

2007-08-17

Q. I have read your article how do I play sound from JavaScript and everything works great. I have arranged for sound on mouseover events and have accomplished that with no difficulty (thanks to you). However, how do I arrange for the sound to play only on the first mouseover?

A. In the script element of your head element, initialize a variable called soundAlready to false. Declaring this variable outside of a particular handler or function makes it global to the page, so that its value is remembered for as long as the user is on the page.

You will set this variable to true after calling soundmanager.play. And if it is already true, you won't call soundmanager.play at all.

The complete solution looks like this.

Important: read the article how do I play sound from javaScript before attempting to use this code! It will not work if you do not install soundmanager properly first.
<html>
<head>
<title>Play Sound On First Mouseover Only</title>
<!-- Bring in soundmanager.js -->
<script type="text/javascript" src="soundmanager.js">
</script>
<script>
<!-- Declare the global variable -->
var soundAlready = false;
<!-- Our one-time sound-playing function -->
function myplay() {
  if (soundAlready) {
    return;
  }
  soundAlready = true;
  soundManager.play('on');
}
</script>
<body>
<h1>Play Sound on First Mouseover Only</h1>
<img src="myimage.png" onMouseOver="myplay()"/>
<!-- A dummy div element, soundManager requires at least one -->
<div>
</div>
<script>
soundManagerInit();
</script>
</body>
</html>


Follow us on Twitter | Contact Us

Copyright 1994-2012 Boutell.Com, Inc. All Rights Reserved.