| 1 |
/* Off-Canvas Drawer — frontend */ |
| 2 |
( function () { |
| 3 |
function init() { |
| 4 |
document.querySelectorAll('.bkoc-wrap[data-position]').forEach(function(wrap) { |
| 5 |
if (wrap._bkocInit) return; |
| 6 |
wrap._bkocInit = true; |
| 7 |
|
| 8 |
var trigger = wrap.querySelector('.bkoc-trigger'); |
| 9 |
var drawer = wrap.querySelector('.bkoc-drawer'); |
| 10 |
var overlay = wrap.querySelector('.bkoc-overlay'); |
| 11 |
var closeBtn = wrap.querySelector('.bkoc-close'); |
| 12 |
if (!trigger || !drawer) return; |
| 13 |
|
| 14 |
var closeOnOverlay = wrap.getAttribute('data-close-overlay') === '1'; |
| 15 |
var closeOnEscape = wrap.getAttribute('data-close-escape') === '1'; |
| 16 |
var overlayEnabled = wrap.getAttribute('data-overlay') === '1'; |
| 17 |
|
| 18 |
function open() { |
| 19 |
wrap.classList.add('bkoc-open'); |
| 20 |
trigger.setAttribute('aria-expanded','true'); |
| 21 |
drawer.removeAttribute('aria-hidden'); |
| 22 |
document.body.style.overflow = 'hidden'; |
| 23 |
// focus first focusable element in drawer |
| 24 |
var firstFocusable = drawer.querySelector('button,a,input,[tabindex]:not([tabindex="-1"])'); |
| 25 |
if (firstFocusable) setTimeout(function(){firstFocusable.focus();},50); |
| 26 |
} |
| 27 |
|
| 28 |
function close() { |
| 29 |
wrap.classList.remove('bkoc-open'); |
| 30 |
trigger.setAttribute('aria-expanded','false'); |
| 31 |
drawer.setAttribute('aria-hidden','true'); |
| 32 |
document.body.style.overflow = ''; |
| 33 |
trigger.focus(); |
| 34 |
} |
| 35 |
|
| 36 |
trigger.addEventListener('click', function(e) { |
| 37 |
e.stopPropagation(); |
| 38 |
if (wrap.classList.contains('bkoc-open')) { close(); } else { open(); } |
| 39 |
}); |
| 40 |
|
| 41 |
if (closeBtn) { closeBtn.addEventListener('click', close); } |
| 42 |
|
| 43 |
if (overlayEnabled && closeOnOverlay && overlay) { |
| 44 |
overlay.addEventListener('click', close); |
| 45 |
} |
| 46 |
|
| 47 |
if (closeOnEscape) { |
| 48 |
document.addEventListener('keydown', function(e) { |
| 49 |
if (e.key === 'Escape' && wrap.classList.contains('bkoc-open')) { close(); } |
| 50 |
}); |
| 51 |
} |
| 52 |
|
| 53 |
// trap focus within drawer when open |
| 54 |
drawer.addEventListener('keydown', function(e) { |
| 55 |
if (e.key !== 'Tab') return; |
| 56 |
var focusableEls = drawer.querySelectorAll('button,a,[tabindex]:not([tabindex="-1"]),input,textarea,select'); |
| 57 |
if (!focusableEls.length) return; |
| 58 |
var first = focusableEls[0], last = focusableEls[focusableEls.length-1]; |
| 59 |
if (e.shiftKey) { if (document.activeElement===first) { e.preventDefault(); last.focus(); } } |
| 60 |
else { if (document.activeElement===last) { e.preventDefault(); first.focus(); } } |
| 61 |
}); |
| 62 |
}); |
| 63 |
} |
| 64 |
|
| 65 |
if (document.readyState === 'loading') { |
| 66 |
document.addEventListener('DOMContentLoaded', init); |
| 67 |
} else { |
| 68 |
init(); |
| 69 |
} |
| 70 |
}() ); |
| 71 |
|