Skip to content

Instantly share code, notes, and snippets.

@lerouxb
Created February 20, 2011 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lerouxb/836285 to your computer and use it in GitHub Desktop.
Save lerouxb/836285 to your computer and use it in GitHub Desktop.
/*
<style>
#detect.child > p,
#detect.firstchild p:first-child,
#detect.lastchild p:last-child,
#detect.nthchild p:nth-child(2n+1),
#detect.sibling b + b {display: block; width: 111px;}
</style>
*/
(function($) {
var tests = [
{name: 'child', selector: '> p'},
{name: 'firstchild', selector: '> p'},
{name: 'lastchild', selector: '> p'},
{name: 'nthchild', selector: '> p'},
{name: 'sibling', selector: 'b + b'}
];
$.fn.detect = function() {
this.each(function() {
var $element = $(this);
$element.append('<div id="detect"><p><b>&nbsp</b><b>&nbsp;</b></p></div>');
var $detect = $element.find('> #detect');
for (var t in tests) {
var test = tests[t];
var name = test.name;
var selector = test.selector;
// remove existing and add the new one
$detect.attr('class', name);
if ($detect.find(selector).width() == 111) {
$element.addClass(name);
} else {
$element.addClass('no-'+name);
}
}
$detect.remove();
});
};
})(jQuery);
<script src="detect.js"></script>
<style>
#detect.child > p,
#detect.firstchild p:first-child,
#detect.lastchild p:last-child,
#detect.nthchild p:nth-child(2n+1),
#detect.sibling b + b {display: block; width: 111px;}
</style>
<script>
$(document).ready(function() {
var $body = $('body');
$body.detect();
var required = ['child', 'firstchild', 'lastchild', 'nthchild', 'sibling'];
var failed = false;
for (var r in required) {
var klass = required[r];
if (!$body.hasClass(klass)) {
failed = true;
break;
}
}
if (failed) {
$('#requirements-failed').css('display', 'block');
} else {
$('#requirements-succeeded').css('display', 'block');
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment