[Solved] Getting position in js [closed]


There are two ways to achieve this…

1) Pure CSS

You can use the position sticky.

body {
  /* ?? Just added, so you can scroll on page */
  height: 200vh;
}

#box {
  margin-top: 80px;
  position: sticky;
  background-color: blueviolet;
  width: 100%;
  height: 80px;
  top: 0;
}
<div id="box"></div>


2) Javascript

Here we are adding a scroll event, which will get fired when we scroll.

this.scrollY indirectly means window.scrollY, and it returns the position of our scrollbar. box.scrollHeight returns the height required to reach the box.

Ans we are comparing them and when they meet our conditions we add .fixed class to the #box.

const box = document.getElementById("box");

window.addEventListener("scroll", () => {
  if (this.scrollY >= box.scrollHeight) box.classList.add("fixed");
  else box.classList.remove("fixed");
});
body {
  /* ?? Just added, so you can scroll on page */
  height: 200vh;
}

#box {
  margin-top: 80px;
  background-color: blueviolet;
  width: 100%;
  height: 80px;
}

#box.fixed {
  margin-top: 0px;
  position: fixed;
  top: 0;
}
<div id="box"></div>


solved Getting position in js [closed]