Skip to content

Instantly share code, notes, and snippets.

@hejrobin
Created May 17, 2014 13:32
Show Gist options
  • Save hejrobin/d68e4822fb330c941bc4 to your computer and use it in GitHub Desktop.
Save hejrobin/d68e4822fb330c941bc4 to your computer and use it in GitHub Desktop.
(function(window, jQuery) {
/**
* ensure
*
* Only invokes callback if selector matches at least one node.
*
* @param string selector
* @param function callback
*
* @dependencies jQuery
*
* @return bool|mixed
*/
var ensure = window.ensure = function(selector, callback) {
var targetNodes = jQuery(selector),
targetNode = targetNodes.eq(0),
numNodes = targetNodes.length;
if(numNodes > 0 && typeof callback === 'function') {
return callback.apply(this, [
jQuery,
targetNode,
targetNodes
]);
}
return false;
};
})(window, jQuery);
(function(window, $) {
ensure('body.no-javascript', function($, target) {
target.removeClass('no-javascript').addClass('has-javascript');
});
ensure('#node.that.doesnt-exist', function($, target) {
// Won't fire
target.data('answer', '42');
});
})(window, jQuery);
@hejrobin
Copy link
Author

hejrobin commented Oct 1, 2015

Maybe change this to something like;

$('some.selector').exists(function() { /* conditional magic */ });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment