scroll js code example

Example 1: how to smooth scroll in javascript

window.scrollTo({ top: 900, behavior: 'smooth' })

Example 2: javascript scroll down

window.scrollTo(300, 500);	//X=300 and Y=500

Example 3: window.scroll

scroll function

window.scroll({
 top: 0, 
 left: 0, 
 behavior: 'smooth' 
});

window.scroll(x-coord, y-coord)
window.scroll(options)

Example 4: js onscroll event

// HTML:
<element onscroll="myScript">
// JavaScript:
object.addEventListener("scroll", myScript)
// or
object.onscroll = function() { /*...*/ }

Example 5: smooth scrolll to id js

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});

Example 6: scroll js

window.scroll(x-coord, y-coord)
window.scroll(options)