portOdin portOdin - 7 months ago 101
Javascript Question

Creating a scroll position indicator in React

I'm trying to code a scroll indicator progress bar in React. I have it working with Jquery but would like to know how to do it with pure Javascript.

componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}

handleScroll() {
var winHeight = $(window).height(),
docHeight = $(document).height(),
value = $(window).scrollTop(),
max, percent;

max = docHeight - winHeight;
percent = (value / max) * 100;
this.props.updatePercent(percent);
}


Also, should I bother doing this in pure Javascript? I've been told that Jquery should not be used used in React.

Answer

Is this the only place you used JQuery? If so, I'd recommend ditching it for pure javascript. Everything you can do with JQuery you can also do with React and pure JavaScript, and it's not worth the overhead here.

Here's a pure JavaScript version of your handleScroll function. Note that document height is notoriously annoying to compute, but I've taken the approach of this question (which just reproduces JQuery's implementation).

handleScroll() {
   var winHeight = window.innerHeight;

   // Annoying to compute doc height due to browser inconsistency
   var body = document.body,
   var html = document.documentElement;
   var docHeight = Math.max( body.scrollHeight, body.offsetHeight, 
                   html.clientHeight, html.scrollHeight, html.offsetHeight );

   var value = document.body.scrollTop;
   ...
}