Skip to content

Instantly share code, notes, and snippets.

@JaeYeopHan
Created January 18, 2019 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JaeYeopHan/c4be75fcc51d87a6f28b9f22e18b60db to your computer and use it in GitHub Desktop.
Save JaeYeopHan/c4be75fcc51d87a6f28b9f22e18b60db to your computer and use it in GitHub Desktop.
progress bar
import React from 'react'
import { throttle } from 'lodash-es'
import './index.scss'
export class ProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
scrollY: 0,
scrollBarRate: 0,
}
this.ScrollRateCalculation = this.ScrollRateCalculation.bind(this)
}
ScrollRateCalculation() {
let innerHeight = window.innerHeight //A
let bodyElement = document.body
let rect = bodyElement.getBoundingClientRect() //B2
let heightIsHtml = rect.height //B3
let scrollMax = Math.ceil(heightIsHtml - innerHeight) //C = B3 - A
let scrollY = document.documentElement.scrollTop || document.body.scrollTop //D
let scrollRate = parseInt((scrollY / scrollMax) * 100, 10) //E = (D / C) *100
this.setState(() => ({
scrollY: scrollY,
scrollBarRate: scrollRate,
}))
}
componentDidMount() {
this.ScrollRateCalculation()
document.addEventListener(
'scroll',
throttle(this.ScrollRateCalculation),
300
)
window.addEventListener('hashchange', this.ScrollRateCalculation)
}
componentWillUnmount() {
document.removeEventListener('scroll', this.ScrollRateCalculation)
window.removeEventListener('hashchange', this.ScrollRateCalculation)
}
render() {
return (
<div className="progress-bar">
<div
className="progress-bar status"
id="hoge"
style={{
width: `${this.state.scrollBarRate}%`,
}}
/>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment