Eunicorn
Eunicorn

Reputation: 621

Scrolling to specific div on click event

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');
});

Upvotes: 2

Views: 2375

Answers (1)

Michel Simões
Michel Simões

Reputation: 234

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>

Upvotes: 1

Related Questions