views:

49

answers:

2

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. The page itself is also vertically scrollable with a scroll bar on the right. I would like to be able to click on a link and have the modal window scroll to the linked item.

I can pretty much achieve this using target.scrollIntoView(); but the entire page scrolls along with the modal window - I would like it so the page does not move and have just the modal window scroll. If I use scrollIntoView(false) the page itself does not scroll, while the modal window does, but the target element is at the bottom of the window while I'd like it at the top.

Is there some way I can manually offset the position of the target within the div? i.e. if I use scrollIntoView(false), the target is displayed at the bottom of the div - if I could then offset it by the height of the view window I should be able to move it to the top..?

Note: I can't use JQuery or the like for this.

Thanks in advance for any help.

A: 

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

Joachim VR
A: 

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)

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

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

function f_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.

Ender
Thanks for the reply - I'll take a look into this. In the meantime, I appear to have achieved what I required by simply setting the div.scrollTop to the offsetTop of the element being linked to.
thor