0

I am trying to add a class when the top of the window scrolls to a specific ID and removes class when scrolls back to the top. i am new to ReactJs and unsure how to accomplish this.

window.onscroll = function() {scrollFunction()};

 scrollFunction() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.getElementById("myID").className = "test";
  } else {
    document.getElementById("myID").className = "";
  }
}

how can i use something like this in React? looking for a simple function that will handle this

3
  • How do find out if the window is scrolled to a particular id? or <a href="#somethin" clicking this link it'll navigate inside the page! Commented May 15, 2020 at 18:16
  • If you don't have the logic! First, we have to find if the id is in viewport! and then we have to write toggle classes! Commented May 15, 2020 at 18:18
  • i think you can use ref and achieve this one Commented May 15, 2020 at 18:22

1 Answer 1

1

You can use var getBoundingClientRect and calculate the viewable element!

I have created stackblitz link to the kind of fixing your problem! If you need further help comment

componentDidMount() {
    const getViewable = document.getElementById("start-editing");
    const that = this;
    window.addEventListener(
      "scroll",
      function(event) {
        if (that.isInViewport(getViewable)) {
          getViewable.classList.add("black");
          getViewable.classList.remove("gold");
        } else {
          getViewable.classList.add("gold");
          getViewable.classList.remove("black");
        }
      },
      false
    );
  }

  isInViewport = elem => {
    var bounding = elem.getBoundingClientRect();
    return (
      bounding.top >= 0 &&
      bounding.left >= 0 &&
      bounding.bottom <=
        (window.innerHeight || document.documentElement.clientHeight) &&
      bounding.right <=
        (window.innerWidth || document.documentElement.clientWidth)
    );
  };
Sign up to request clarification or add additional context in comments.

1 Comment

yep this is what i was looking for! thanks for the help. new to react and trying to wrap my head around it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.