Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fire a javascript playsound event onclick without sending the user to the top of the page?

I have the following code on a page on my site — when the user clicks on the image a sound plays:

<script language="javascript" type="text/javascript">
 function playSound(soundfile) {
 document.getElementById("dummy").innerHTML=
 "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
 }
 </script>
 <span id="dummy"></span>
 <div id="soundimage">
 <a href="#" onclick="playSound('sound.mp3');"><img src="image.png" /></a>
 </div>

It all works great, but the image is at the bottom of the page, and when the user clicks the image they are redirected back to the top of the page. Is there any way to get this working so that there is only an audio change, and not a visual one (if that makes sense!)?

When using a mouseover function instead, such as

<a onmouseover="playSound('sound.mp3');"><img src="image.png" /></a>

the user remains where they were on the page, but I would like them to have the option of playing the sound on click and not on rollover.

like image 775
JD2011 Avatar asked Dec 19 '11 01:12

JD2011


2 Answers

The problem is your href attribute. # as an anchor sends it to the top of the page. Use

<a href="javascript: void(0);" onclick="playSound('sound.mp3');">...</a>

Also, always include an href attribute to links.

like image 88
Grexis Avatar answered Oct 19 '22 16:10

Grexis


You can (and I think is more correct in cases where Javascript support is limited), to use a link like:

<a href="#" onclick="playSound('sound.mp3'); return false;">...</a>

instead of Grexis one, because if the browser you're using doesn't support Js, then the "onclick" event will never be fired and thus Js won't be read. It won't be a problem, probably, but still you should consider using better coding techniques.

like image 23
Alejandro Iván Avatar answered Oct 19 '22 14:10

Alejandro Iván