What is the best way to accurately scroll a DIV element using javascript / jquery

So I have a page filled with DIV and on page load I need the browser to automatically scroll to the pre-assigned DIV.

I semi-successfully do it like this

$('html,body').animate({scrollTop:jQuery('#mydiv').position().top}, 'slow');

      

The problem is that if the page contains images above #mydiv, the scroll will not be very accurate. This is because when loading images, the browser moves the content (including #mydiv) downward (this is with Safari).

Solutions that didn't work for me:

1) Give all images a given width and height in such a way that the browser knows in advance what their dimensions are and won't push the content on load. This doesn't work for me because the images are all from all over the internet and are not hosted on my own server, so I just don't know their sizes ahead of time (these are user-submitted photos).

2) Start scrolling the page after the page is fully loaded. This is not a starter for me either, because it takes a few seconds to load images (many images) and at that time when the user starts scrolling his browser window and then he suddenly goes to #mydiv. This becomes very confusing and frustrating for the user.

What am I hoping for there are ideas / pointers / code for other solutions? Or am I out of luck what I am trying to accomplish?

+3


source to share


2 answers


You can handle the animation yourself instead of letting $.animate

it be done. This way you can continually check that the top of the div scrolls to and keeps scrolling until you get there. As you upload images and make changes, position().top

you will know that you still need to go further. The problem here is that if you get to load all the images, it pops up again.



// in pseudocode
var myInterval = setInterval(function(){ 
    // get the value of the position().top
    // check that value against the current scrollTop value
    // if not equal or greater than, scroll a little bit
    // else clear myInterval
}, 16); // play with the timer to get best effect

      

0


source


The problem is that you cannot know the dimensions of the images before loading them.

The only logical solution is to add load times to your page and not display anything until the images are loaded. Check if the images are loaded using imagesLoaded instead $(window).load(function()

(as the window loading will wait for all assets, including the footer javascript files), then render the page and highlight the desired section.



In addition, since the page is not displayed initially, the user will also not be able to trigger scrolling and get confused.

0


source







All Articles