Toggle arbitrary attributes in jQuery

jQuery has a toggle function, which toggles whether an element is visible or not, as well as toggleClass, which toggles whether an element has a class. But I frequently want to toggle other attributes, particularly the title. This plugin lets you do that.

(function ($) {
$.fn.toggleAttr = function (attr, val1, val2) {
///<summary>Toggles an attribute between having one of two possible states</summary>
///<param name="attr">Attribute name</param>
///<param name="val1">First value</param>
///<param name="val2">Second value</param>
return this.each(function () {
var $this = $(this);
if ($this.attr(attr) === val1) {
$this.attr(attr, val2);
} else {
$this.attr(attr, val1);
}
});
};
}
)(jQuery);
view raw toggleAttr.js hosted with ❤ by GitHub

No comments:

Post a Comment