Add css class when element is in view

Viewed 46

I have this pretty common use case. Apply a css class when the element is in view. I came across this code which is a great use but I'd like to apply a class to a specific element when it comes into view. Not when the scroll reaches a specific part of the screen. Hopefully with vanilla JS, any ideas. I'm thinking the getElementById needs to be used in some fashion, also would this also be possible only for mobile?

import React, { useState } from 'react';
import './App.css';

function ScrollEffect() {

   const [state, setstate] = useState(false);

  const changeClass = () => {
    const scrollValue = document.documentElement.scrollTop;

    if(scrollValue > 200)
    {
      setstate(true);
    }
    else{
      setstate(false);
    }
      
  }
  window.addEventListener('scroll', changeClass);

  return (
    <div className="App">
      <h1 className={ state ? "blue" : "" }>Hello, World</h1>
    </div>
  )
}

export default ScrollEffect;
1 Answers

There is Browser API made exactly for this use case, its called IntersectionObserver, it will trigger callback, when selected dom element is in view.

You can use some libraries, or you can implement it by yourself.

Great answer for creating custom hook is here

Api Documentation

Related