jQuery - scrolling inside a div? scrollTo?

anonymous picture anonymous · Feb 4, 2011 · Viewed 29.1k times · Source

I have a div container with list in it, only one item of this list is visible at once and the rest is being hidden (the container has overflow: hidden).

I want jQuery to show the requested items after clicking exact links:

http://jsfiddle.net/ztFWv/

Any ideas? Will scrollTo help me? I've tried this plug but no luck. I'd rather not use an iframe.

Answer

Dutchie432 picture Dutchie432 · Feb 4, 2011

ScrollTo would help, but is scrolling absolutely required? I think it's even better to just use slideUp() and slideDown()

I modified the HTML just a bit to give the slide items a class and an id.

Live Demo: http://jsfiddle.net/ztFWv/1/

<div id="slider">
    <ul>
        <li id="one" class="slideItem">
            <h1>Header #1</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc dictum, ante a lacinia pharetra, ligula augue vestibulum urna, gravida placerat odio ipsum eget augue.</p>
        </li>
         <li id="two" class="slideItem">
            <h1>Header #2</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc dictum, ante a lacinia pharetra, ligula augue vestibulum urna, gravida placerat odio ipsum eget augue.</p>
        </li>
         <li id="three" class="slideItem">
            <h1>Header #3</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc dictum, ante a lacinia pharetra, ligula augue vestibulum urna, gravida placerat odio ipsum eget augue.</p>
        </li>
</div>

        <a href="javascript:void(0);" class="one">Scroll to #1</a> 
        <a href="javascript:void(0);" class="two">Scroll to #2</a>
        <a href="javascript:void(0);" class="three">Scroll to #3</a>       

JS

$('a').click(function(){
    var linkClass=$(this).attr('class');
    $('.slideItem:visible').slideUp('fast',function(){
        $('#' + linkClass).slideDown('fast');
    });
});

UPDATE

If you must have scrolling :)

Here is a sample: http://jsfiddle.net/ztFWv/3/

Include the scrollTo JS file and use the command this way.

$('a').click(function(){
    $('#slider').scrollTo( $('#' + $(this).attr('class')), 800 );
});