InnerHTML causes unwanted scrolling in Chrome

I have a simple setup: when clicking on an image, I need an mp3 file.

From most of the sources that I remember, it is recommended that you create a dummy range item in which an audio player can be embedded to automatically start when the image is clicked.

Here's a function to do something like this:

<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>

      

HTML code for image:

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

      

I have placed the "dummy" span at the very bottom of the page. When the image is clicked, the sound plays, but incredibly frustrating is that the page automatically scrolls to the location of that span.

I tried this in IE and Firefox: this problem does not occur. It is 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? How to get rid of this annoying scroll?

return false;

doesn't help (none of them, the second one just shows scrolling up with an attribute #

). Also does not exist preventDefault()

. Nor does the a attribute change href

from #

to javascript:void(0)

.

+3


source to share


2 answers


Instead of using a dummy element, span

I found that Javascript has a method play()

for elements audio

and video

DOM, so I just rewrote the code to avoid Chrome's bug. Apparently it is not supported for IE8 or older, but it is worth the tradeoff.



<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>

      

+5


source


Ok, I ran into a similar problem and found this, but it didn't work for me, I solved a workaround, so I decided to post it here to help other people with the same problem. The problem is that the browser shows that this is happening in response to the user clicking on something, it has to scroll to automatically display the new html content. The workaround I came up with is as follows:

setTimeout(function(){
    document.getElementById('dummy').innerHTML += "THE STUFF";
}, 0);

      



It just makes a setTimeout for 0ms and then adds the html code, this way it doesn't bind to the click event.

0


source







All Articles