Skip to content
Advertisement

Show Button only particular area while scrolling

Need to show Button between 370px to 410px while scrolling in the Page.

useEffect(() => {
    document.addEventListener('scroll', () => {
      try {
        if ((document.body.scrollTop < 410 || document.documentElement.scrollTop < 410) && (document.body.scrollTop > 370 || document.documentElement.scrollTop > 370)) {
          setBtn(true);
        } else {
          setBtn(false);
        }
      } catch (e) {
        console.error(e);
      }
    });
  }, [Btn]);

{Btn ? <button>Submit</button> : null}

Suggest me, how to solve this because this above code is not working.

Advertisement

Answer

The problem with your validation is that using an || operator using two ways of getting the scrollTop is causing your issues, because in chrome document.body.scrollTop returns 0, and that guarantees that the first part of your condition will always be true. So you need to separate for each way of getting the scrollTop

In other words, your if should have this instead:

((document.body.scrollTop < 410 && document.body.scrollTop > 370) || (document.documentElement.scrollTop < 410 && document.documentElement.scrollTop > 370))

Also here’s a better explanation of the scrollTop problem

Advertisement