Today I needed some JS-Code for toggling an DOM elements attribute. Because there is no such feature in the jQuery core, I implemented it. Perhaps it’s useful for you, so here it is :)
Code
jQuery.fn.toggleAttr = function(attribute, value) {
value = value || attribute;
return this.each(function() {
var attr = jQuery(this).attr(attribute);
if (typeof attr !== typeof undefined && attr !== false) {
jQuery(this).removeAttr(attribute);
}
else {
jQuery(this).attr(attribute, value);
}
});
};
When you do not give a value, it’s assumed that you want to toggle attributes like
disabled or selected, so the value is automatically adjusted the attribute
name. Have a look at the example:
Usage
// For example, you have a multiple select control:
// <select multiple="multiple" size="5" id="my-select">
// <option>Option 1</option>
// <option>Option 2</option>
// <option>Option 3</option>
// <option>Option 4</option>
// <option>Option 5</option>
// </select>
// You can easly add a "invert selection"-method, which toggles all items
$('#my-select option').toggleAttr('selected', 'selected');
// is the same as (with missing value parameter)
$('#my-select option').toggleAttr('selected');