Home > OS >  How to change My div position on page-load and on page scroll
How to change My div position on page-load and on page scroll

Time:06-04

I have a top bar div under an element I am trying to show when page reload it has top:50px and when user scroll page the position change to top:175px as I have stick header too, but it is not working as expected.

it is behaving like this on page load - enter image description here

and it has to look like this on page load -

enter image description here

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

    function scrollFunction() {
       if (!document.body.scrollTop > 1 || document.documentElement.scrollTop > 1 ) {
           document.getElementById("bar").style.top = "90px";
      }else{
           document.getElementById("bar").style.top = "175px";
      }
    }

CodePudding user response:

First of all, your if statement is always true because I believe, document.body.scrollTop is always 0 (Correct me if I'm wrong) document.body.scrollTop Firefox returns 0 : ONLY JS. Just use document.documentElement.scrollTop alone:

if (!document.documentElement.scrollTop) {
   // Page load
   document.getElementById("bar").style.top = "90px";
}else{
   // user scrolled
   document.getElementById("bar").style.top = "175px";
}

Second of all, I'm wondering why do you want your bar lower when user scrolled than when the page first loaded? If you want your bar to always be on the page under your header, I suggest you should use css position: sticky; top: *your header height in px*

  • Related