Skip to content

Commit

Permalink
docs(Layout): fix scroll to anchor
Browse files Browse the repository at this point in the history
  • Loading branch information
levithomason committed Feb 23, 2017
1 parent ecf91c4 commit 82cdbe9
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions docs/app/Components/Layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,39 @@ export default class Layout extends Component {
}

resetPage = () => {
window.scrollTo(0, 0)
clearTimeout(this.scrollStartTimeout)

scrollTo(0, 0)

anchors
.add('h2, h3, h4, h5, h6')
.remove([1, 2, 3, 4, 5, 6].map(n => `.rendered-example h${n}`).join(', '))
.remove('.no-anchor')

this.scrollStartTimeout = setTimeout(this.scrollToAnchor(), 2000)
this.scrollStartTimeout = setTimeout(this.scrollToAnchor, 500)
}

scrollToAnchor = () => {
const anchor = location.hash && document.querySelector(location.hash)

// no scroll to target, stop
if (!anchor) return

const elementTop = Math.round(anchor.getBoundingClientRect().top)

if (elementTop !== 0) {
const step = Math.ceil(elementTop / Math.max(15 - Math.log(elementTop), 1))
window.scrollBy(0, step)
requestAnimationFrame(this.scrollToAnchor)
}
// scrolled to element, stop
if (elementTop === 0) return

// hit max scroll boundaries, stop
const isScrolledToTop = scrollY === 0
const isScrolledToBottom = scrollY + document.body.clientHeight === document.body.scrollHeight
const scrollStep = Math.ceil((Math.abs(elementTop / 8))) * Math.sign(elementTop)

if (isScrolledToBottom && scrollStep > 0 || isScrolledToTop && scrollStep < 0) return

// more scrolling to do!
scrollBy(0, scrollStep)
requestAnimationFrame(this.scrollToAnchor)
}

render() {
Expand Down

0 comments on commit 82cdbe9

Please sign in to comment.