I've got a JavaScript function which gets executed when the page loads, and then automatically on a set time-interval. The function cycles through images which are supplied in another script (generated by PHP). But whenever this function manipulates the DOM, the page scrolls back to the top of the div containing the div I'm editing. And I would really like to avoid that!
I've already looked at the other posts on stackOverflow and other websites, but they all involve a user's action, and usually jQuery or Ajax and a link with an anchor. None of that applies in this situation.
To give you an idea of my HTML:
<div id="the_rest_of_my_page">
<div id="scrolls_to_the top_of_this">
<div id="img_div">
This is where my JavaScript is doing stuff
</div>
</div>
</div>
My JavaScript code:
function advance_slideshow( )
{
document.getElementById( img_div ).innerHTML = '<img src="' + img_array[index] + '">';
index = (index+1) % img_array.length;
setTimeout('advance_slideshow()', swap_delay);
}
The problem is quite serious, as the page automatically scrolls up every so many seconds, and there's plenty of important content lower down on the page.
Does anyone know how to prevent this scrolling?
EDIT: Now that I try it again, the page scrolls to the top of the page after editing the DOM, not to the top of the div. That would make more sense I guess, but it's actually even worse!
What I said in comments seems to be the source of your problem : the height of your img is not set, and the parent div have neither height nor min-height.
So, what happens ? When you replace your image, there's some microseconds where there's no actual image in the div : the old one has been discarded, the new one is loading.
No images = 0 height for your parent div. The whole page is shorter, the scroll jumps to top.
Possible solution : a min-height on the div in CSS, or computing the image dimensions and setting width and height when you append them.
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