jqueryjquery-selectorsscrolljavascriptjquery-scrollable

Scrolling jquery question. How to auto scroll onclick to a div


Just wondering if its possible to scroll to a certain div's position on a page onclick. I can't seem to find anywhere on the internet where this is documented.

My idea is to click a button, and it will take you to the position of that div on the page, possible by the div ID.

Regards,

Taylor


Solution

  • Im not sure when you want the event to fire so here is the generic version

    $(selector).click(function() {
       //scroll to div
    });
    

    If you want a <button/> with an id of myButton that when clicked will cause you to scroll to a <div/> with and id of myDiv over the course of half a second:

    $('#myButton').click(function() {
       //optionally remove the 500 (which is time in milliseconds) of the
       //scrolling animation to remove the animation and make it instant
       $.scrollTo($('#myDiv'), 500);
    });
    

    Using the jQuery ScrollTo plugin.