Skip to content

scrollIntoView() smooth animation is finally available on Chrome

kdaisho edited this page Dec 30, 2017 · 3 revisions

Great News

IF you are a logger, a logger who cuts down jQuery trees on your sites, plants clean trees called vanilla in place. Here's our latest win. Chrome has silently started to take arguments on scrollIntoView method which almost everyone sets to 'smooth'.

jQuery

<!-- From -->
<button href="#dest-01" class="scroll-from">Learn More</button>
<button href="#dest-02" class="scroll-from">Shop Now</button>

<!-- To -->
<a class="dest-01"></a>
<h2>Learn More</h2>

<a class="dest-02"></a>
<h2>Shop Now</h2>

<script>
$('.scroll-from').click(function(e) {
    e.preventDefault(); // disable the hyperlink
    var href = $(this).attr('href');
    href = href.replace('#', '');
    var togo = $('a[class="' + href + '"]');

    $('html,body').animate({
        scrollTop:togo.offset().top - hy_offset
    }, 500)
});
</script>

Vanilla

<!-- From -->
<a href="#about" class="link">ABOUT</a>
<a href="#work" class="link">WORK</a>

<!-- To -->
<a class="dest-link"></a>
<h2 class="about">About Us</h2>

<a class="dest-link"></a>
<h2 class="work">Our Work</h2>

<script>
//Get nav-buttons and destination anchor elements then convert them into an array
var links = document.getElementsByClassName("link"),
dest_links = document.getElementsByClassName("dest-link");

links = [].slice.call(links);
dest_links = [].slice.call(dest_links);

function clickListener(link, i) {
    link.addEventListener("click", function() {
        dest_links[i].scrollIntoView({behavior: "smooth"});
    }, false);
}

for (var i = 0, len = links.length; i < len; i++) {
    clickListener(links[i], i);
}
</script>
Clone this wiki locally