javascriptactionscript-2onscrollonscrolllistener

Change JavaScript scroll top to a id or class rather than body


I have a side menu that sticks to the top of the page. rather than using the body to tell the position can I change it to a div, call or id.

My current code this code tells the side menu to position itself according to a class once i have scrolled 40px from the top of the page, how do i change it so its 40px from a ID or class?

 window.onscroll = function () {onScrollNav()};

function onScrollNav() {
   if (document.body.scrollTop > 40 || document.documentElement.scrollTop > 40) {
        document.getElementById("mySidenav").className = "sidenavScroll";
        console.log("you hit 40px !!");
    } else {
        document.getElementById("mySidenav").className = "sidenavScrollReset";
        console.log("you back to 0 !!");
    }
}

Solution

  • I think your best bet is to get the scroll position, the offset of the element with the ID in question and lastly do some quick maths.

    var elOffset = document.getElementById('<ID HERE>').getBoundingClientRect();
    function onScrollNav() {
        var diff = (document.documentElement.scrollTop - elOffset.top);
        if (diff > 40) {
            document.getElementById("mySidenav").className = "sidenavScroll";
            console.log("you hit 40px offset from the element with ID!!");
        } else {
            document.getElementById("mySidenav").className = "sidenavScrollReset";
            console.log("you back to 0 !!");
        }
    }