-1

I'm asking this because I'm trying to get the distance between the viewport top and a scrollable element top, then when it meets a specific value, I will use it in an If statement.

example:

if (viewport.top > div.top) {
  div.style.background = "blue";
} else {
  div.style.background = "red";
}
  • if this was possible, does that value go negative when the element is out of viewport?
  • is the viewport top always = 0 ?

please help me understand this.

thank you.

  • Explain what is a *"Scrollable element top"* and why the fact that it's scrollable matters?! You mean... An element inside the scrolling viewport? There are hundreds of answers online on how to get an element's top from viewport. Which one the provided codes have you tried and why it did not worked? Why do you think that if an element goes out of the top scroll area your value would not be negative? – Roko C. Buljan May 13 '22 at 14:27
  • A scrollable element is an element that goes hidden out of the viewport when scrolling up or down. like the div I provided in the example. just a normal simple div. – Ahmed Barea May 13 '22 at 14:32
  • Yes. Logically. If an element goes beyond the top scroll area, the value **will be negative**. – Roko C. Buljan May 13 '22 at 14:33
  • ok I found half the answer I'm looking for here: https://stackoverflow.com/a/49672072/6467902. now if I want to use this value in if statement, do I compare it to window.top or what? – Ahmed Barea May 13 '22 at 14:48
  • That answer is correct `distanceFromTop` is exactly what is says it is. The distance of the element top from the viewport top. What else do you need on top of that value? Test your application variables using https://developer.mozilla.org/en-US/docs/Web/API/console/log – Roko C. Buljan May 13 '22 at 15:12
  • now if I want to use this value in if statement, do I compare it to window.top or what? – Ahmed Barea May 13 '22 at 15:21
  • Your question makes no sense. What is `window.top`? Have you tried to `console.log(window.top)` ? What do you expect it to be? If you already have the **signed distance**... what else do you need more? – Roko C. Buljan May 13 '22 at 16:01
  • if the distance between the div.top and viewport.top is more than 100px, change div color to blue. I hope this can deliver my idea. please be patient with me. – Ahmed Barea May 17 '22 at 12:14

0 Answers0