How can I scroll to a specific location on the page using jquery?
Asked Answered
M

11

135

Is it possible to scroll to a specific location on the page using jQuery?

Does the location I want to scroll to have to have:

<a name="#123">here</a>

Or can it just move to a specific DOM id?

Micronesian answered 18/10, 2009 at 23:37 Comment(4)
just a small note: attribute "name" is not allowed in XHTML 1.1 Strict, use an ID insteadSpiteful
interesting question, can't use page coordinates to scroll? I think we should be able to.Oilskin
I got solution similar to your requirement at [here][1] [1]: #3433156Iqbal
@Micronesian does your problem resolved?Galway
S
242

jQuery Scroll Plugin

since this is a question tagged with jquery i have to say, that this library has a very nice plugin for smooth scrolling, you can find it here: http://plugins.jquery.com/scrollTo/

Excerpts from Documentation:

$('div.pane').scrollTo(...);//all divs w/class pane

or

$.scrollTo(...);//the plugin will take care of this

Custom jQuery function for scrolling

you can use a very lightweight approach by defining your custom scroll jquery function

$.fn.scrollView = function () {
    return this.each(function () {
        $('html, body').animate({
            scrollTop: $(this).offset().top
        }, 1000);
    });
}

and use it like:

$('#your-div').scrollView();

Scroll to a page coordinates

Animate html and body elements with scrollTop or scrollLeft attributes

$('html, body').animate({
    scrollTop: 0,
    scrollLeft: 300
}, 1000);

Plain javascript

scrolling with window.scroll

window.scroll(horizontalOffset, verticalOffset);

only to sum up, use the window.location.hash to jump to element with ID

window.location.hash = '#your-page-element';

Directly in HTML (accesibility enhancements)

<a href="#your-page-element">Jump to ID</a>

<div id="your-page-element">
    will jump here
</div>
Spiteful answered 18/10, 2009 at 23:52 Comment(3)
Thanks @Juraj Blahunka, but I do this without any pluginGalway
The link is not taking me to ScrollTo. Can you update it please?Hectometer
This should be the answer!Horseman
A
130

Yep, even in plain JavaScript it's pretty easy. You give an element an id and then you can use that as a "bookmark":

<div id="here">here</div>

If you want it to scroll there when a user clicks a link, you can just use the tried-and-true method:

<a href="#here">scroll to over there</a>

To do it programmatically, use scrollIntoView()

document.getElementById("here").scrollIntoView()
Annulose answered 18/10, 2009 at 23:47 Comment(2)
@Annulose This is not supported yet everywhere. caniuse.com/#search=scrollIntoViewHaydon
This i def supported (developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView). Think you didn't read the caniuse properly. However, won't be animated. Rather a pretty abrupt jump which isn't always great.Yahrzeit
G
56

There is no need to use any plugin, you can do it like this:

var divPosition = $('#divId').offset();

then use this to scroll document to specific DOM:

$('html, body').animate({scrollTop: divPosition.top}, "slow");
Galway answered 22/6, 2013 at 7:6 Comment(5)
+1 This is probably the best answer. Not much code and does not require a plugin.Mining
Note that you might need to recalculate the offset on window resize.Coady
@BartBurg good point-- or just recalculate right before the .animate call happensHarrietteharrigan
Love the simple answer. Why do people have to make things so complicated? Don't want another plugin.Sluggard
Indeed the best answer.Horsetail
B
21

Here's a pure javascript version:

location.hash = '#123';

It'll scroll automatically. Remember to add the "#" prefix.

Barajas answered 18/10, 2009 at 23:49 Comment(2)
Using the primitive way of named anchor, you can have URL that includes the hash E.g. mywebsite.com/page-about/#123 Bookmarking includes the hash + scrollintoview behaviour too.Barajas
Would be great if you can explain a littleDaria
J
7

Plain Javascript:

window.location = "#elementId"
Jacquetta answered 19/8, 2014 at 21:30 Comment(0)
W
6
<div id="idVal">
    <!--div content goes here-->
</div>
...
<script type="text/javascript">
     $(document).ready(function(){
         var divLoc = $('#idVal').offset();
         $('html, body').animate({scrollTop: divLoc.top}, "slow");
     });
</script>

This example shows to locate to a particular div id i.e, 'idVal' in this case. If you have subsequent divs/tables that will open up in this page via ajax, then you can assign unique divs and call the script to scroll to the particular location for each contents of divs.

Hope this will be useful.

Wye answered 18/9, 2013 at 21:34 Comment(0)
C
4
<script type="text/javascript">
    $(document).ready(function(){
        $(".scroll-element").click(function(){
            $('html,body').animate({
                scrollTop: $('.our_companies').offset().top
            }, 1000);

            return false;
        });
    })
</script>

Cyrus answered 16/12, 2014 at 13:14 Comment(1)
It would be great if you add some comments to your code. How does it helps the asker to solve their question?Forepaw
C
1

Try this

<div id="divRegister"></div>

$(document).ready(function() {
location.hash = "divRegister";
});
Cluck answered 6/12, 2016 at 12:10 Comment(0)
E
0

Here is variant of @juraj-blahunka's lightweight approach. This function does not assume the container is the document and only scrolls if the item is out of view. Animation queuing is also disabled to avoid unnecessary bouncing.

$.fn.scrollToView = function () {
    return $.each(this, function () {
        if ($(this).position().top < 0 ||
            $(this).position().top + $(this).height() > $(this).parent().height()) {
            $(this).parent().animate({
                scrollTop: $(this).parent().scrollTop() + $(this).position().top
            }, {
                duration: 300,
                queue: false
            });
        }
    });
};
Evenfall answered 5/10, 2015 at 21:33 Comment(1)
I had the bounce issue, but your method doesn't workUnmeasured
P
0

Using jquery.easing.min.js, With fixed IE console Errors

Html

<a class="page-scroll" href="#features">Features</a>
<section id="features" class="features-section">Features Section</section>


        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="js/jquery.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Scrolling Nav JavaScript -->
        <script src="js/jquery.easing.min.js"></script>

Jquery

//jQuery to collapse the navbar on scroll, you can use this code with in external file with name scrolling-nav.js
        $(window).scroll(function () {
            if ($(".navbar").offset().top > 50) {
                $(".navbar-fixed-top").addClass("top-nav-collapse");
            } else {
                $(".navbar-fixed-top").removeClass("top-nav-collapse");
            }
        });
        //jQuery for page scrolling feature - requires jQuery Easing plugin
        $(function () {
            $('a.page-scroll').bind('click', function (event) {
                var anchor = $(this);
                if ($(anchor).length > 0) {
                    var href = $(anchor).attr('href');
                    if ($(href.substring(href.indexOf('#'))).length > 0) {
                        $('html, body').stop().animate({
                            scrollTop: $(href.substring(href.indexOf('#'))).offset().top
                        }, 1500, 'easeInOutExpo');
                    }
                    else {
                        window.location = href;
                    }
                }
                event.preventDefault();
            });
        });
Portfolio answered 27/7, 2018 at 12:39 Comment(1)
That is way too much code for such a simple task. location.hash = 'idOfElement'; should sufficeHager
C
0

You can use scroll-behavior: smooth; to get this done without Javascript

https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior

Chamberlain answered 3/11, 2018 at 5:52 Comment(3)
scroll-behavior: smooth; is not browser compatible property.Portfolio
check the browser compatibility lower in the link - developer.mozilla.org/en-US/docs/Web/CSS/…Chamberlain
Yes given table in your links is showing: Edge, IE and safari are not compatible with this property.Portfolio

© 2022 - 2024 — McMap. All rights reserved.