0

I Have a button at the top, 4 tables in the middle and a div (id="MasterDiv") on the bottom of a page. How can I scroll to the div automatically when I click the button? Thanks

Karim Ali
  • 2,243
  • 6
  • 23
  • 31

4 Answers4

6

You can use this function (which uses jQuery's .animate)

function scrollToElement(selector, callback){
    var animation = {scrollTop: $(selector).offset().top};
    $('html,body').animate(animation, 'slow', 'swing', function() {
        if (typeof callback == 'function') {
            callback();
        }
        callback = null;
    });
}

You call it like this:

scrollToElement('#MasterDiv');

Or if you want to include a callback:

scrollToElement('#MasterDiv', function(){
  alert('Page scrolled');
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • That function is from a question I asked: http://stackoverflow.com/questions/5019951 – gen_Eric Feb 16 '11 at 20:48
  • You should consider accepting that answer from your previous question (http://stackoverflow.com/questions/5019951/scroll-to-element-on-page-and-then-run-callback) then since you're reposting it here as your own and the original answerer never got credit from the check mark. – iwasrobbed Feb 16 '11 at 21:08
  • @iWasRobbed: I never said it was my function, I gave a link to the question, where you can see someone else made that. – gen_Eric Feb 16 '11 at 21:10
  • @Rocket: Understood, I was just noting that the original answerer never got the check mark :) – iwasrobbed Feb 16 '11 at 21:13
2
Example
A named anchor inside an HTML document:

<a name="tips">Useful Tips Section</a>
Create a link to the "Useful Tips Section" inside the same document:

<a href="#tips">Visit the Useful Tips Section</a>
Or, create a link to the "Useful Tips Section" from another page:

<a href="http://www.w3schools.com/html_links.htm#tips">
Visit the Useful Tips Section</a>

source

Jeff
  • 1,871
  • 1
  • 17
  • 28
1

You could try this library: http://demos.flesler.com/jquery/scrollTo/

Erik
  • 4,268
  • 5
  • 33
  • 49
0

No animation basic Javascript Example (use ID instead of the name attribute)

window.location = "#MasterDiv";

More on window.location

Jquery Animation Example

$.scrollTo("#MasterDiv");

ScrollTo Jquery Plugin