8

I have a div with a class overflow: auto; Is there a way to control this scrollbar when it appears?

I have a ajax photo gallery (no page refresh) where some caption text is in a div, but the content is of varying length. If you scroll down in this div and then advance to the next slide, the scrollbar does not go back to the top. So, I was wondering if there was a way to control this scrollbar. Thanks.

4 Answers 4

7

With jQuery, you can set the top of the scroll area like so:

$('#contents').scrollTop(0);

Here's a demo showing this in action->

Note that this is also possible without jQuery:

document.getElementById('contents').scrollTop = 0;

And a demo of that->

For both demos, press the Reset button to set the scroll bar back to the top.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the suggestion. Let me investigate this as well.
I'm awarding the answer to Ender.
4

You can change the value of the property scrollTop of the <div> element.

See element.scrollTop on MDC docs

See element.scrollTop on MSDN

While scrollTop is not part of any standard, it is supported by all major browsers.

1 Comment

Interesting. Thanks. Let me investigate this.
4

To move the vertical bar back to the top on an overflowed element myControl , you must do

$("#myControl").scrollTop(0);

or, in case of horizontal bar, to move it to the beginning (left)

$("#myControl").scrollLeft(0);

If you want to hide the scroll bars, you must do this CSS

#myControl {
    overflow: hidden;
}

You are assuming that the next slide resides on the top. If you have absolute positionated slides, you might better do the following, to ensure that you scroll to the correct nextSlide location:

var nextSlidePos = $("#slide" + nextSlide).position();
$("#myControl").scrollTop( nextSlidePos.top ).scrollLeft( nextSlidePos.left );

Comments

1

Update after a test, using elm.scrollTop = 0:

<div style="overflow:auto;height:100px;width:100px">
    <p>test</p>
    <p>test</p>
    <p>test</p>
    <a href="javascript:" onclick="this.parentNode.scrollTop = 0">go up</a>
</div>

2 Comments

This is not the browser's scrollbar. This is the scrollbar that appears on the div, because it has a overflow: auto CSS declaration. The content is appearing inside the div.
I've never used it but did you try div.scrollTo(x, y) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.