2

I have a div with a class of "second". I would like to scroll to that element in the page when a button is clicked. Below is how I wrote it using jQuery but I'd like to know how to write this in vanilla JavaScript?

$("button").click(function() {
    $('html,body').animate({
        scrollTop: $(".second").offset().top},
        'slow');
});
chazsolo
  • 7,873
  • 1
  • 20
  • 44
Eunicorn
  • 601
  • 6
  • 16
  • 29
  • What research have you done so far and have you made any attempt(s) of you own to do this without `jQuery`? If so please include them to your question as this can help give a detailed answered to explain why your attempt didn't function as intended and maybe give a detailed solution. **Edit:** Also an example of the `HTML` would be good since I see this `jQuery` selector is targeting a `class` name of `second` so it would be helpful to know which `class` you want to relate to depending on the `button` clicked. – NewToJS Nov 03 '17 at 02:42
  • For firefox, you can use [scorllTo](https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo). But you will potentially run into issues for Chrome. See [here](https://stackoverflow.com/questions/15691569/javascript-issue-with-scrollto-in-chrome) – jrook Nov 03 '17 at 02:44
  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! Also see [ask]. – Hubert Grzeskowiak Nov 03 '17 at 02:44

1 Answers1

1

function getPosition(element) {
        var e = document.getElementById(element);
        var left = 0;
        var top = 0;

        do {
            left += e.offsetLeft;
            top += e.offsetTop;
        } while (e = e.offsetParent);

        return [left, top];
    }

    function jumpTo(id) {
        window.scrollTo(getPosition(id));
    }
<a href="#one" onclick="jumpTo('one');">One</a>

<div style="height: 900px"></div>
<div id="one"></div>
Michel Simões
  • 234
  • 3
  • 8