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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With