views:

70

answers:

1

I have a page that has three divs one at the top, one at the side, and one content div in the bottom left. The content div contains a series of divs. and I want a button that allows you to step through them highlighting them one at a time. However, the content div contains more data than can fit on a screen, and so I put it in an overflow: scroll. Now I need to ensure that the highlighted div in the content is visible as the user clicks through.

I have tried various techniques recommended here and other web sites, but they all scroll the page not the content div, meaning my header and side bar scroll out of view. Can anyone give me some pointers on how to scroll just the overflow div. Here is some simplified sample code of what I am doing.

First the HTML:

    <div id='header'>
        Header
        <input type="button" id="NextButton" value="Next" />
    </div>
    <div id='content' style="overflow: scroll">
        <div id="div1" class='highlight'> Text for div1 </div>
        <div id="div2"> Text for div2 </div>
        <div id="div3"> Text for div3 </div>
        <div id="div4"> Text for div4 </div>
        <div id="div5"> Text for div5 </div>
    </div>
</div>
<div id='sidebar' style="float:right">
    Sidebar
</div>

Now the JavaScript (Note obviously it is using jQuery)

    var current;
    $(document).ready(function () {
        var current = $('#div1');
        $('#NextButton').click(function() {
            current.removeClass('highlight');
            current = current.next();
            current.addClass('highlight');
          // Somehow make content scroll to the top of the div#content  
        })
    });

FWIW, here is the style element:

    .highlight { color: Red; }

As you see the click on the #NextButton moves through the divs changing the highlight, however, I also need to ensure that div is actually visible, such as by scrolling it to the top. (BTW, I know that it doesn't check for the end, I am just stripping it down to the minimum for simplicity.)

Any help would be appreciated.

A: 

The jQuery plugin ScrollTo works on individual elements. The trouble is knowing if an element is shown or not. Depending on browser compatibility this may not always be possible. You can 'cheat' by always scrolling, however this can seem a bit jittery for users.

Metalshark