Created
June 18, 2011 19:48
-
-
Save Wilto/1033446 to your computer and use it in GitHub Desktop.
Test/polyfill for native “details”/“summary” support.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* TODO: Something about keyboard support. */ | |
(function(win, undefined){ | |
support = { | |
detailToggle : function() { | |
var fakeBody, | |
doc = document, | |
de = doc.documentElement, | |
bod = doc.body || (function() { | |
fakeBody = true; | |
return de.insertBefore(doc.createElement('body'), de.firstElementChild || de.firstChild); | |
}()), | |
det = doc.createElement('details'), | |
div = doc.createElement('div'), | |
txt = doc.createTextNode('W'), | |
ret; | |
div.style.visibility = 'hidden'; | |
div.appendChild(txt); | |
det.appendChild(div); | |
bod.appendChild(det); | |
ret = div.offsetHeight === 0; | |
bod.removeChild(det); | |
fakeBody && bod.parentNode.removeChild(bod); | |
return ret; | |
} | |
}; | |
$('details').each(function(i) { | |
var $el = $(this), | |
$tog = $el.children('summary'), | |
$content = $el.children('div'), | |
open = $el.attr('open'); | |
$el.attr({ | |
'aria-expanded' : open, | |
'aria-labelledby' : 'label-' + i | |
}); | |
$content.attr({ | |
id : 'content-' + i, | |
'aria-hidden' : !open | |
}); | |
$tog.attr({ | |
id : 'label-' + i, | |
'aria-controls' : 'content-' + i | |
}) | |
.click(function(e) { | |
var open = $el.attr('open') || $content.is(':visible'); | |
$el.attr( 'aria-expanded', !open ); | |
$content.attr( 'aria-hidden', open ); | |
!support.detailToggle() && $content.toggle(); | |
}); | |
}); | |
})(this); |
@paulirish Yeah, very true—I should’ve put a link to that page in a comment somewhere. Mathias’ test definitely seems like it would be more robust than mine, especially given the display: block
addition. Didn’t think of that one.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mathiasbynens did something similar here fwiw http://mathiasbynens.be/notes/html5-details-jquery