Skip to content

Instantly share code, notes, and snippets.

@ChristianRich
Last active May 10, 2016 00:16
Show Gist options
  • Save ChristianRich/b5f2bec298d63e50c11f8e2418dcce87 to your computer and use it in GitHub Desktop.
Save ChristianRich/b5f2bec298d63e50c11f8e2418dcce87 to your computer and use it in GitHub Desktop.
jQuery plugin determining if an element contains named data-attributes and that their values are non empty
$.fn.extend({
/**
* jQuery plugin determining if an element contains named data-attributes and that their values are non empty
* Usage:
*
* <button id="myButton" data-country="australia" data-city="sydney" data-some-empty-value="">
*
* $('#myButton').hasDataAttrib('country') // true
* $('#myButton').hasDataAttrib('data-country') // true
* $('#myButton').hasDataAttrib(['country']) // true
* $('#myButton').hasDataAttrib(['data-country']) // true
* $('#myButton').hasDataAttrib('some-empty-value']) // false
* $('#myButton').hasDataAttrib(['country', 'city']) // true
* $('#myButton').hasDataAttrib('banana') // false
* $('#myButton').hasDataAttrib(['country', banana']) // false
*
* @param {string|array} attribs A single attribute or an array of attributes.
* @returns {boolean}
*/
hasDataAttrib: function (attribs) {
if(typeof _ === 'undefined'){
throw new Error('jQuery plugin hasDataAttrib requires lodash.');
}
var test = function($el, attrib){
// Removes the "data-" part of the attribute if present
if(attrib.indexOf('data-') !== -1){
attrib = attrib.substr(5, attrib.length);
}
return !_.isUndefined($el.data(attrib)) && String($el.data(attrib)).length !== 0;
};
var $target = this,
res = true;
if($target.length === 0){
throw new Error('Selector expected')
}
if($target.length > 1){
throw new Error('Multiple selectors not supported')
}
if(_.isUndefined(attribs)){
throw new Error('Parameter attribute expected')
}
if(_.isString(attribs)){
return test($target, attribs);
}
else if(_.isArray(attribs)){
_.each(attribs, function(attrib){
if(!test($target, attrib)){
res = false;
}
});
}
else{
throw new Error('String or Array expected for parameter attrib');
}
return res;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment