user8758206
user8758206

Reputation: 2191

Class not toggling correctly if scrolltop exceeds limit

I'm trying to get it that when you scroll 1500 (pixels?) down, the absolute div at the bottom disappears, and then reappears if scrolling back up (where the scrolltop is back to under 1500).

Not sure why, but the div seems to flash randomly whenever the scrolltop exceeds 1500; it should just disappear, and reappear when back within range.

Why is the effect malfunctioning? It's supposed to just toggle with the class that displays it to none. Thanks for any help.

window.onscroll = function() {if ((window.innerHeight + window.scrollY) >= 1500) {document.getElementById('test').classList.toggle("customstyle")}};
body {
  height: 2000px;
  background: #ccc;
}
.customstyle {display: none}
<body>
<div id="test" style="
    position: fixed;
    bottom: 0;
    background:  red;
    left: 0;
    padding: 20px;
    width: 100%;
    text-align:  center;
">text</div>
  </body>

Upvotes: 0

Views: 31

Answers (3)

Sergey
Sergey

Reputation: 7682

window.onscroll = function() {
  if (window.scrollY >= 1500) {
  
    document.getElementById('test').classList.add("customstyle")
  
  } else {
    document.getElementById('test').classList.remove("customstyle")
  }

};
body {
  height: 2000px;
  background: #ccc;
}
.customstyle {display: none}
<body>
<div id="test" style="
    position: fixed;
    bottom: 0;
    background:  red;
    left: 0;
    padding: 20px;
    width: 100%;
    text-align:  center;
">text</div>
  </body>

Upvotes: 1

epascarello
epascarello

Reputation: 207527

What you are saying if the condition is true than toggle the class so every time it checks it is toggleing the class when it it true so it flashes.

You want to use the Boolean as the second argument.

document.getElementById('test').classList.toggle("customstyle", window.innerHeight + window.scrollY >= 1500)

Upvotes: 2

Gaunt
Gaunt

Reputation: 714

Because you are toggling the class(thus adding and removing the class each time your scroll event get called when you are over 1500px), you should add the class when you passed the 1500 px, and then remove it when you are below 1500 px:

window.onscroll = function() {
    if ((window.innerHeight + window.scrollY) >= 1500) {
        document.getElementById('test').classList.add("customstyle");
    } else {
        document.getElementById('test').classList.remove("customstyle");
    }
};

Upvotes: 1

Related Questions