Skip to content

Instantly share code, notes, and snippets.

@tremby
Last active December 24, 2015 13:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tremby/6804168 to your computer and use it in GitHub Desktop.
Save tremby/6804168 to your computer and use it in GitHub Desktop.
Jquery toggleAttr plugin, which toggles the (boolean) attribute for each element or, if given a second parameter toggles the attribute of each element to that value, like toggle(bool) and toggleClass(class, bool) do.
$.fn.toggleAttr = (attr, bool) ->
if bool
return @attr attr, attr
if typeof bool isnt 'undefined'
return @removeAttr attr
@each ->
$e = $ @
if typeof $e.attr(attr) is 'undefined'
$e.attr attr, attr
else
$e.removeAttr attr
$.fn.toggleAttr = function(attr, bool) {
if (bool) {
return this.attr(attr, attr);
}
if (typeof bool !== 'undefined') {
return this.removeAttr(attr);
}
return this.each(function() {
var $e = $(this);
if (typeof $e.attr(attr) === 'undefined') {
$e.attr(attr, attr);
} else {
$e.removeAttr(attr);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment