Skip to content Skip to sidebar Skip to footer

Scrolling To An Element Within A Div

I have an absolutely positioned div which acts as a modal window in the center of the page. The modal window is vertically scrollable with a scroll bar on the right hand side. Th

Solution 1:

Here's a live demo that I think does what you're looking for: http://jsfiddle.net/QN3mK/

The code to do it is this: (mostly check the scrollFunc() function)

functionscrollFunc() {
    var est = document.getElementById('est');
    var docPos = f_scrollTop();
    est.scrollIntoView();
    window.scrollTo(0,docPos);
}

functionf_scrollTop() {
    return f_filterResults (
        window.pageYOffset ? window.pageYOffset : 0,
        document.documentElement ? document.documentElement.scrollTop : 0,
        document.body ? document.body.scrollTop : 0
    );
}

functionf_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

The second two functions are just a cross-browser compatible way that I found of getting the current scroll position of a page. So what this does is find an element (presumably within a scrollable div), gets the current scroll position of the page, scrolls the element into view (which will put it at the top of the scrollable div) and then resets the page position back to where it was. Probably not an ideal solution, but it will get the job done.

Solution 2:

You could experiment with assigning integer values to the scrollTop property.

Post a Comment for "Scrolling To An Element Within A Div"