views:

15

answers:

0

I created a jQuery function that applies a class to a paragraph, and then scrolls to that paragraph when a button is clicked. It works fine when the paragraphs are relative to the document, but I want the scroll to happen inside a div. Currently, the scrolling is working, and it is applying the class correctly, but it is does not scroll to the correct paragraph. It seems that it's scrolling to a random one each time the button is clicked.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
        $(function() {

                $('.down').click(function() {
                    $('.current + p').addClass('current');
                    if ($('p:last').hasClass('current')) {
                        $('p').removeClass('current');
                        $('p:last').addClass('current');
                        return false;                   
                    }
                    else {
                    $('.current:first').removeClass('current');
                    return false;
                    }
                });

                $('.up').click(function() {
                    $('.current').prev('p').addClass('current');
                    if ($('p:first').hasClass('current')) {
                        $('p').removeClass('current');
                        $('p:first').addClass('current');
                        return false;
                    }
                    else {
                    $('.current:last').removeClass('current');
                    return false;
                }
            });
            $('.down, .up').click(function() {
                $('.slider').animate({scrollTop: $(".current").offset().top},'slow');
            });
        });
</script>

<style type="text/css">
.slider {
position: relative;
background: #ccc;
overflow: scroll;
height: 100px;
}
.slider p {
position: relative;
}
.nav {
position: fixed;
left: 500px;
z-index: 10;
}

p {
height: 100px;
}
</style>

</head>

<body>

<div class="nav">
<a href="#" class="up">UP</a>
<a href="#" class="down">DOWN</a>
</div>

<br /><br />
<div class="slider">
<p class="current">This is the first paragraph</p>
<p>111111111111111111111111</p>
<p>222222222222222222222222</p>
<p>333333333333333333333333</p>
<p>44444444444444444444444444</p>
<p>This is the last paragraph</p>
</div>


</body>
</html>

To see it when it works, change ".slider" in the CSS to height: 1000px and no overflow. Also, change this line:

$('.slider').animate({scrollTop: $(".current").offset().top},'slow');

to this:

$('html,body').animate({scrollTop: $(".current").offset().top},'slow');