Skip to content

Instantly share code, notes, and snippets.

@jlbruno
Last active September 29, 2015 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jlbruno/1689211 to your computer and use it in GitHub Desktop.
Save jlbruno/1689211 to your computer and use it in GitHub Desktop.
elementQuery
// call elementQuery and pass it an object containing the tests.
// also pass it an object containing a 'passed' callback and a 'failed' callback
// you can also pass a bool for whether you want to bind this to be run on resize
$('#torso').elementQuery({ 'min-width' : 910 , 'max-width' : 1155}, {
passed : function() {
$(this).addClass('l-full').removeClass('l-xlarge');
},
failed : function() {
$(this).removeClass('l-full');
}
}, true);
$('#torso').elementQuery({ 'min-width' : 1155 }, {
passed : function() {
$(this).addClass('l-xlarge').removeClass('l-full');
},
failed : function() {
$(this).removeClass('l-xlarge');
}
}, true);
(function( $ ) {
$.fn.elementQuery = function(propsObj, callbacks, bind) {
var $el = this;
var checkFunc = function(win) {
var passed = false;
for (var key in propsObj) {
passed = false;
var cssProp = key;
var cssVal = propsObj[key];
if (cssProp === "min-width") {
if ( $el.width() < cssVal) break;
} else if (cssProp === "max-width") {
if ( $el.width() > cssVal) break;
} else {
if ( $el.css(cssProp) !== cssVal+'px') break;
}
passed = true;
}
if (passed) {
if (callbacks.passed && typeof(callbacks.passed) === "function") {
// execute the callback, passing parameters as necessary
callbacks.passed.call($el);
}
} else {
if (callbacks.failed && typeof(callbacks.failed) === "function") {
// execute the callback, passing parameters as necessary
callbacks.failed.call($el);
}
}
};
if (bind) {
$(window).one('load.elementQuery', function(e) {
checkFunc(this);
});
$(window).on('resize.elementQuery', function(e) {
checkFunc(this);
});
}
return this;
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment