Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

innerHTML causes unwanted scroll in Chrome

I have a simple set up: upon clicking an image, I want an mp3 file to play.

From most sources that I recall, the recommendation is to create a dummy span element where one can embed an audio player to auto start upon clicking the image.

Here's the function to perform such an action:

<script language="javascript" type="text/javascript">
  function playSound(soundfile,evt) {
    document.getElementById("dummy").innerHTML = "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
    evt.preventDefault(); // this doesnt do anything
    return false; // neither does this
  }
</script>

The HTML code for the image:

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

I placed the "dummy" span at the very bottom of the page. Upon clicking the image, the sound plays, but the incredibly annoying thing is that the page automatically scrolls down to the location of this span element.

I've tried this on IE and Firefox: this problem doesn't occur. It's only in the most recent version of Chrome (24.0.1312.56 m) that this happens. I have tried this on two computers.

Does anyone know what's up? How do you get rid of this annoying scroll?

The return false; doesn't help (neither of them; the second one just presents scrolling to the top via the # attribute). Neither does the preventDefault(). Neither does changing the a href attribute from # to javascript:void(0).

like image 433
ergo Avatar asked Dec 06 '25 08:12

ergo


1 Answers

Instead of using a dummy span element, I found out that there is a play() method in Javascript for the audio and video DOM elements, so I just rewrote the code to avoid the Chrome bug. Apparently, it's not supported for IE8 or older versions, but it's a worthwhile trade-off.

<audio id="aud">
    <source src="aud.ogg" type="audio/ogg" />
    <source src="aud.mp3" type="audio/mpeg" />
</audio>
<a href="#" onClick="document.getElementById('aud').play(); return false;">
  Link
</a>
like image 136
ergo Avatar answered Dec 08 '25 22:12

ergo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!