Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate scroll to ID on page load

People also ask

How do I scroll to a certain div on page load?

Just get the div id from query string and on page load pass it to above code like: $('#' + divToScrollTo). offset(). top , where divToScrollTo is js variable where we have stored the query string value.

How do you scroll to the bottom of the div on load?

Use scrollTop and scrollHeight to Scroll to the Bottom of Div in JavaScript. A combination of scrollTop and scrollHeight can cause an element to scroll to the bottom because scrollTop determines the number of pixels for a vertical scroll. In contrast, scrollHeight is the element's height (visible and non-visible parts) ...

How do you scroll automatically to the bottom of the div using jquery?

To auto scroll a page from top to bottom we can use scrollTop() and height() method in jquery. In this method pass the document's height in scrollTop method to scroll.


You are only scrolling the height of your element. offset() returns the coordinates of an element relative to the document, and top param will give you the element's distance in pixels along the y-axis:

$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);

And you can also add a delay to it:

$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);

Pure javascript solution with scrollIntoView() function:

document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
<h2 id="title1">Some title</h2>

P.S. 'smooth' parameter now works from Chrome 61 as julien_c mentioned in the comments.


Deprecation Notice: The jQuery.browser property was removed in jQuery 1.9. Visit the docs for more details: https://api.jquery.com/jQuery.browser/

$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);

Source: jQuery Animate Body Scroll For All Browsers


There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check this link.

In your case the code is

$("#title1").animatedScroll({easing: "easeOutExpo"});

try with following code. make elements with class name page-scroll and keep id name to href of corresponding links

$('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });