Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. const FOCUSABLE = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex]:not([tabindex="-1"]), [contenteditable]'
  2.  
  3. export default class Modal {
  4.   constructor (options) {
  5.     const focusableChildren = options.el.querySelectorAll(FOCUSABLE)
  6.     this.el = options.el
  7.     this.activeClass = options.activeClass
  8.     this.firstFocusableChild = focusableChildren[0]
  9.     this.lastFocusableChild = focusableChildren[focusableChildren.length - 1]
  10.     this.elBeforeOpen = null
  11.     this.scrollBeforeOpen = null
  12.     this._onKeydown = this._onKeydown.bind(this)
  13.   }
  14.  
  15.   show () {
  16.     this.scrollBeforeOpen = document.documentElement.scrollTop
  17.     this.elBeforeOpen = document.activeElement
  18.     document.body.setAttribute('style', [
  19.       'position: fixed',
  20.       'width: 100%',
  21.       'top: ' + -this.scrollBeforeOpen + 'px'
  22.     ].join(';'))
  23.     document.addEventListener('keydown', this._onKeydown)
  24.     this.el.classList.add(this.activeClass)
  25.     this.firstFocusableEL.focus()
  26.   }
  27.  
  28.   hide () {
  29.     document.body.removeAttribute('style')
  30.     document.documentElement.scrollTop = this.scrollBeforeOpen
  31.     document.removeEventListener('keydown', this._onKeydown)
  32.     this.el.classList.remove(this.activeClass)
  33.     this.elBeforeOpen.focus()
  34.   }
  35.  
  36.   _onKeydown (e) {
  37.     if (e.key === 'Tab') {
  38.       if (e.shiftKey) {
  39.         if (document.activeElement === this.firstFocusableChild) {
  40.           e.preventDefault()
  41.           this.lastFocusableChild.focus()
  42.         }
  43.       } else {
  44.         if (document.activeElement === this.lastFocusableChild) {
  45.           e.preventDefault()
  46.           this.firstFocusableChild.focus()
  47.         }
  48.       }
  49.     }
  50.     if (e.key === 'Escape') {
  51.       e.preventDefault()
  52.       this.hide()
  53.     }
  54.   }
  55. }
  56.  
  57. const modal = new Modal({
  58.   el: document.querySelector('.modal'),
  59.   activeClass: '.modal--active'
  60. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement