All files ScrollLock.js

100% Statements 20/20
100% Branches 7/7
100% Functions 5/5
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47    4x 4x 4x       2x               1x                 1x 1x 1x 1x 1x 1x       3x 2x 2x       2x 1x 1x 1x      
export default class ScrollLock {
  constructor() {
    this.currentPos = 0
    this.tag = null
    this.head = document.head
  }
 
  getCurrentPos() {
    return (
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop
    )
  }
 
  createStyleTag() {
    const css = `
      body {
        overflow: hidden !important;
        position: fixed;
        top: -${this.currentPos}px;
        left: 0;
        width: 100%;
      }
    `
    let tag = document.createElement('style')
    tag.type = 'text/css'
    tag.setAttribute('data-react-scrolllock', '')
    tag.appendChild(document.createTextNode(css))
    this.head.appendChild(tag)
    this.tag = tag
  }
 
  on() {
    if (!this.head) return
    this.currentPos = this.getCurrentPos()
    this.createStyleTag()
  }
 
  off() {
    if (!this.tag) return
    this.head.removeChild(this.tag)
    this.tag = null
    window.scrollTo(0, this.currentPos)
  }
}