Why isn’t my function changing the background as expected?

Asked

Viewed 43 times

1

I’m trying to change the transparency of mine header based on the scroll of the screen. To do so, I created a eventListener of scroll triggering the following function:

function solidHeader(){
    if (document.getElementById('crossfade').getBoundingClientRect().bottom < 60) {
        setTypeBackground('solid')
    } else {
        setTypeBackground('transparent')
    }
}

The goal is that when the bottom of <div id="crossfade" /> touch the bottom of header, what happens when the <div id="crossfade" /> is 60px from the top of the page, the function change the status of typeBackground for 'solid'. With this, it is expected that the useEffect:

window.addEventListener('scroll', solidHeader)
useEffect(() => {
    /* A tag de id="Card" é o header */
    document.getElementById('Card').style.backgroundColor = typeBackground
}, [typeBackground])

fire, altering the property backgroundColor of header for 'solid'. But that doesn’t happen. Why?

It may be important to mention that this function is being implemented in a sister component of header:

function App() {
    return (
        <div id="super-container">
            <AuthProvider>
                /* Esse é o header que quero alterar: */
                <Header />
                <Switch>
                    /* esse é o componente que monitora o scroll e tenta alterar a propriedade: */
                    <Route exact path="/" component={Home} />
                    <Route path="/servicos" component={Servicos} />
                    <Route path="/teste" component={AreaCliente} />
                </Switch>
            </AuthProvider>
        </div>
    );
};

export default App;

1 answer

0

Hello, I confess that I did not understand your problem, but taking into consideration this section below, maybe I can help...

I’m trying to change the transparency of my header based on scroll screen.

I created a simple example that meets this statement, maybe it’s not exactly what you need, but you can easily modify it to meet your need.

https://codesandbox.io/s/scroll-8sxdp

  • Bruno, grateful for the willingness to try to help. But if you don’t understand the question, it’s a sign that you shouldn’t be answering. Your answer seems to fit much more into a comment. Note that although your code solves the problem, it does not answer the question. Having said that, your code was useful for me to try to adopt another approach to scroll monitoring. What I was using was really heavy

  • Hello, thanks for the feedback, I posted an answer because I’m new to stackoverflow, and so I still can not comment on questions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.