Skip to content

Instantly share code, notes, and snippets.

@jbuncle
Created November 26, 2015 23:32
Show Gist options
  • Save jbuncle/2f9a4eb78e868e09f046 to your computer and use it in GitHub Desktop.
Save jbuncle/2f9a4eb78e868e09f046 to your computer and use it in GitHub Desktop.
jQuery Plugin to toggle an elements attribute
/*!
* jQuery Toggle Attribute
*
* Copyright 2013 James Buncle
*
* Released under the MIT license.
* http://jquery.org/license
*
*/
(function($) {
/**
* Adds/removes the given attribute using the value provided
*
* @param name the name of the attribute to toggle
* @param the attribute value to use when toggling the attribute on
* @returns the jQuery object
*/
$.fn.toggleAttr = function(name, value) {
return this.each(function() {
var $obj = $(this);
var currentAttr = $obj.attr(name);
if (currentAttr !== undefined && currentAttr !== false) {
$obj.removeAttr(name);
} else {
$obj.attr(name, value);
}
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment