brad_fresh
brad_fresh

Reputation: 129

The element doesn't change color when scrolling back on top the page

here's a fiddle I want to change the color of the "@" element on the page after I scroll the navigation bar.

enter image description here

It works but only when I scroll down.

enter image description here

When I scroll on top of the page it doesn't work. As a result, @ stays red coloured when expected to be white.

enter image description here

window.addEventListener("scroll", (event) => {
    if (!document.querySelector('.container')) return;
    let container = document.querySelector('.container');

    if (container.scrollHeight - container.scrollTop === container.clientHeight) {
        document.querySelector('.chat-icon').style.color = "red";
    } else
        document.querySelector('.chat-icon').style.color = "white";
});

P.S. white element is the one of "container" class and violet is a navigation bar.

Upvotes: 0

Views: 318

Answers (1)

Dumitru Birsan
Dumitru Birsan

Reputation: 837

that would be because the div cannot be scrolled and the variable container.scrollTop returns 0 mozzila docs

If the element can't be scrolled (e.g. it has no overflow or if the element has a property of "non-scrollable"), scrollTop is 0.

instead you can use window.scrollY

window.addEventListener("scroll", (event) => {
let container = document.querySelector('.nav');
if (container.scrollHeight - window.scrollY === container.clientHeight) {
    document.querySelector('.chat-icon').style.color = "red";
} else
    document.querySelector('.chat-icon').style.color = "white";
});

here's a working a example

Upvotes: 1

Related Questions