A simple jQuery plugin for toggling attributes, similar to how toggleClass
works for CSS classes. Created so that if-else
constructs like the following:
// 'unsavedChanges' is a boolean value
if (unsavedChanges) {
$('button#save').removeAttr('disabled');
} else {
$('button#save').attr('disabled', 'disabled');
}
can become:
$('button#save').toggleAttr('disabled', 'disabled', !unsavedChanges);
Include the jQuery library first, and then the toggleAttr plugin:
<script src="toggleattr.jquery.js" type="text/javascript></script>
Call toggleAttr
on an element:
$('#someElement').toggleAttr(<attrName>, <attrValue>, <stateVal>)
The only required parameter is <attrName>
- <attrValue>
and <stateVal>
are
both optional. <stateVal>
is used for the same purpose as the optional second
parameter to jQuery core's toggleClass
- if true, it forces the attribute to
be added; if false, it forces the attribute to be removed.
HTML before:
<input type="text" />
JS:
$('input').toggleAttr('myattr');
HTML after:
<input type="text" myattr />
JS:
$('input').toggleAttr('myattr');
HTML after:
<input type="text" />
HTML before:
<div></div>
JS:
$('div').toggleAttr('myattr', 'myValue');
HTML after:
<div myattr="myValue"></div>
HTML before:
<div myattr="myValue"></div>
JS:
$('div').toggleAttr('myattr', 'myValue', true);
HTML after:
<div myattr="myValue"></div>
If the <stateVal>
parameter is true and the attribute already exists, the value
will be updated to <attrValue>
:
JS:
$('div').toggleAttr('myattr', 'myNewValue', true);
HTML after:
<div myattr="myNewValue"></div>
The plugin is licensed under the MIT License.
- v1.0.0: First release