Fix an element when it reaches the top of the screen using javascript and css

I have an element that I want to stick on top after it reaches the top of the screen.

<div id="HeaderWrapper">
  ...
  <div id="Navigation">
    Navigation
  </div>
  ...
</div>

I add an event listener on scroll, which calls a function to check the placement of an element using the method getBoundingClientRect(). If topeither the yelement is less than 0 relative to the viewport, I would like to fix / insert the title. Again, if it is greater than 0, I would like to remove the commit position. In both cases, I add and remove the name of a class fixed_navbarthat has a fixed position property.

document.addEventListener("scroll", function() {
  const el = document.getElementById("Navigation");
  let rect = el.getBoundingClientRect();
  if (rect.top <= 0) {
    el.classList.add("fixed_navbar");
  } else {
    el.classList.remove("fixed_navbar");
  }
});

You can also check out the codepen demo .

, . , 0, . , , 0, - . , , , , ?

+4
3

CSS, :

position: sticky

position: sticky; top (. top: 0;), , , "".

:

header {
height: 600px;
}

.navigation {
position: sticky;
top: 0;
margin-top: 150px;
}
<header>
<div class="navigation">Navigation</div>
</header>
Hide result

:

position: sticky :

https://caniuse.com/#feat=css-sticky

+2

 if (rect.top <= 0) {

, rect.top < 0,

+1

@Rounin provides an awesome solution. Although I will fix your problem in JavaScript. you can check it out

document.addEventListener("scroll", function() {
  const el = document.getElementById("Navigation");
  let rect = el.getBoundingClientRect();
  if (rect.top <= 0) {
    el.classList.add("fixed_navbar");
  } else {
   window.onscroll = function() {myFunction()};

function myFunction() {
    if ( document.body.scrollTop < 100 ) {
        el.classList.remove("fixed_navbar");
    } 
  }
  }
});
* {
  margin: 0;
  padding: 0;
}

#HeaderWrapper {
  background: lightgrey;
  height: 1500px;
}

.box {
  background: skyblue;
  width: 100%;
  height: 100px;
}

#Navigation {
  background: green;
}

.fixed_navbar {
  position: fixed;
  z-index: 1000;
  width: 100%;
  left: 0;
  top: 0;
}
<div id="HeaderWrapper">
  <div class="box"></div>
  <div id="Navigation">
    Navigation
  </div>
</div>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1687516/


All Articles