Skip to content

Commit

Permalink
Update details polyfill
Browse files Browse the repository at this point in the history
  • Loading branch information
gemmaleigh committed Sep 7, 2017
1 parent c6707e0 commit 12a87b2
Showing 1 changed file with 41 additions and 10 deletions.
51 changes: 41 additions & 10 deletions app/assets/javascripts/details.polyfill.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@

// http://www.sitepoint.com/fixing-the-details-element/

(function () {
;(function () {
'use strict'

var NATIVE_DETAILS = typeof document.createElement('details').open === 'boolean'
var KEY_ENTER = 13
var KEY_SPACE = 32

// Add event construct for modern browsers or IE
// which fires the callback with a pre-converted target reference
Expand All @@ -25,25 +27,50 @@
}
}

// Cross-browser character code / key pressed
function charCode (e) {
return (typeof e.which === 'number') ? e.which : e.keyCode
}

// Cross-browser preventing default action
function preventDefault (e) {
if (e.preventDefault) {
e.preventDefault()
} else {
e.returnValue = false
}
}

// Handle cross-modal click events
function addClickEvent (node, callback) {
// Prevent space(32) from scrolling the page
addEvent(node, 'keypress', function (e, target) {
if (target.nodeName === 'SUMMARY') {
if (e.keyCode === 32) {
if (e.preventDefault) {
e.preventDefault()
// When the key gets pressed - check if it is enter or space
if (charCode(e) === KEY_ENTER || charCode(e) === KEY_SPACE) {
if (target.nodeName.toLowerCase() === 'summary') {
// Prevent space from scrolling the page
// and enter from submitting a form
preventDefault(e)
// Click to let the click event do all the necessary action
if (target.click) {
target.click()
} else {
e.returnValue = false
// except Safari 5.1 and under don't support .click() here
callback(e, target)
}
}
}
})
// When the key comes up - check if it is enter(13) or space(32)

// Prevent keyup to prevent clicking twice in Firefox when using space key
addEvent(node, 'keyup', function (e, target) {
if (e.keyCode === 13 || e.keyCode === 32) { callback(e, target) }
if (charCode(e) === KEY_SPACE) {
if (target.nodeName === 'SUMMARY') {
preventDefault(e)
}
}
})
addEvent(node, 'mouseup', function (e, target) {

addEvent(node, 'click', function (e, target) {
callback(e, target)
})
}
Expand Down Expand Up @@ -89,6 +116,10 @@
details.__summary = details.getElementsByTagName('summary').item(0)
details.__content = details.getElementsByTagName('div').item(0)

if (!details.__summary || !details.__content) {
return
}

// If the content doesn't have an ID, assign it one now
// which we'll need for the summary's aria-controls assignment
if (!details.__content.id) {
Expand Down

0 comments on commit 12a87b2

Please sign in to comment.