Joel Eckroth
Joel Eckroth

Reputation: 2534

Scroll a div 30px when anchor clicked

What's the best way to scroll a div with overflow:auto by a certain pixels or certain percentage when clicking an anchor? The HTML is very simple:

<style>
#container{
height:250px;
overflow:auto;
</style>

<div id="container">
<p>Lots of Content</p>
</div>

<a href="#" id="scrolldiv">Scroll Down</a>

When I click the anchor above, I want to scroll that div above a certain amount of pixes, say 30px. I'm hoping jQuery has something built in that makes this simple.

Upvotes: 1

Views: 4150

Answers (2)

Teneff
Teneff

Reputation: 32158

For that purpose I would use jQuery's animate:

$('#scrolldiv').click(function(){
    $('#container').animate({scrollTop: '+=30'});
});

I belive it's got the shortest syntax for this and it looks nice.

jsFiddle example

Upvotes: 1

Sinetheta
Sinetheta

Reputation: 9429

$('#scrolldiv').click(function(e){
    var current = $('#container').scrollTop();
    $('#container').scrollTop(current + 30);
    e.preventDefault();
});​

jsFiddle

Upvotes: 6

Related Questions