12

I want the page to scroll to a div that's at the top of the page. I have buttons for other parts of the page, but this isn't working when I scroll to the bottom and click on the button. It doesn't go to the top of the page.

Here is the CodePen: https://codepen.io/Filizof/pen/xygWyp?editors=1010

$(document).ready(function() {
    $("#btn1").click(function() {
        $("body").scrollTo("#menudiv");
    });
});
3
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behaviour, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Commented Oct 16, 2018 at 9:59
  • I think it is removed in 3.3.1 You can try something like this codepen.io/dholakiyaankit/pen/LgeRbE Commented Oct 16, 2018 at 10:00
  • 1
    Finally found which "the button" you're referring to. Open your browser's console and you'll see this error: Uncaught TypeError: $(...).scrollTo is not a function - because jquery does not have a scrollTo function. Commented Oct 16, 2018 at 10:05

6 Answers 6

50

Vanilla JavaScript


If you would like to scroll to an element smoothly with "pure JavaScript" you could do something like this:

document.querySelector('#menudiv').scrollIntoView({
    behavior: 'smooth'
});

More information is here: Element.scrollIntoView()

NOTE: Please see Can I use... Support tables for HTML5, CSS3, etc. for the latest browser support...

jQuery


If you would like to scroll to an element smoothly using jQuery then you could do something like:

$(document).ready(function() {
  $(".btns").click(function() {
    $("html").animate(
      {
        scrollTop: $("#menudiv").offset().top
      },
      800 //speed
    );
  });
});

Example: https://jsbin.com/xaciloteqe/1/edit?html,js,output


This might be helpful for people researching this topic:

“Cancelable” Smooth Scrolling

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

7 Comments

For the first time I have seen a clean and less code for the same task in pure javascript compared to jquery.
"Pure Javascript" example still uses jQuery to select the click event - why not offer a 100% pure js answer if you claim it to be?
@RichardEdwards the original question was about "scrolling an element using Jquery." I also provided an answer on scrolling using pure javascript so he could see how easy it was (and IMHO even easiier than JQuery!). If the person with the question wants to convert the rest of his code to javascript then that is up to him as that was not what the question was about.
@MWD - still was not a "pure js" solution, wrapping pure js in jquery != pure js - still requires jquery - this is unclear for others viewing your code example - which I notice you have now removed to avoid such confusion.
If you select body,html then you scroll two times. You can simply use $("html").animate()
|
9

JavaScript has the element.scrollIntoView() function.

Something like:

$("#menudiv")[0].scrollIntoView()

1 Comment

If you want to use pure javascript & don't want any scrolling animations then itay's answer is easy to use - see codepen.io/anon/pen/MPrbGy
3

You can use simple JS to get this done. scrollIntoView() scrolls to visible area.

Something like this:

var elmnt = document.getElementById("content");
elmnt.scrollIntoView();

Comments

0
<script type="text/javascript" src="jquery-3.2.1.js">

replace with

<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>

1 Comment

The codepen already uses 3.3.1 - are you saying 'scrollTo' is new in 3.3.1 but not in 3.2.1? What other benefit would changing the jquery version have? How does this answer sole the question?
0

I had a little problem due to some markdownify plugin, anyway I had to search for the link's target so I used this work around. Its actually working for a variety of element selectors, in my case my link was <a href="#target">some text</a> and my actual target was <a href="target"></a> for this particular case I can give you that solution:

var scrollAnchorSamePage = function() {
    $('a[href^="#"]').click(function() {
      event.preventDefault();
      var id  = $(this).attr("href");

      // okay lets remove the hashtag in front:
      var target = $('a[href^="' + id.substring(1, id.length) + '"]');

      // and I need a little offset due to a fixed sticky header by 140
      $('html, body').animate({ scrollTop: target.offset().top - (160)  }, 1000);
    });
}

scrollAnchorSamePage();

PS: I use following imports of jQuery packages, you can add them right before your closing </body> html tag in your DOM.

<!-- Latest minified jQuery -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<!-- Latest compiled and minified bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

Comments

0

I update your code a little bit, it should be:

 $(document).ready(function() {
  $("#btn1").click(function()
 {
   var elmnt = document.getElementById("menudiv");
   elmnt.scrollIntoView();
 });
});

To scroll to a div/element, it is the scrollIntoView HTML DOM method. It is not a jQuery function.

Here is the code pen: JS Scroll to an Element

Comments

Your Answer

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