Best way to disable button in Twitter's Bootstrap
Immediately disable a Bootstrap button by setting its disabled
attribute. In JavaScript, toggle the button's disabled
property to true
.
Example in JavaScript:
In HTML, simply add disabled
:
This renders the button unclickable and visually faded, following Bootstrap's disabled state styling.
Diving into the disabled attribute
The disabled
attribute is more than meets the eye. It both visually fades out the element and disables user interaction. However, <a>
tags are the rebellious child and won’t respect the disabled
attribute natively. In such cases, use .disabled
class for visual consistency and explicitly prevent clicks with event listeners:
Keeping things consistent across browsers
From Firefox to Chrome, the disabled
attribute behaves consistently. However, for the users' sake (and our sanity) always thoroughly test:
- Test all supported browsers.
- Update accessibility attributes such as
aria-disabled
. - For
<input>
elements, use.prop('disabled', true)
ordisabled
attribute. It's the same game, new player. - Ensure any associated JavaScript event handlers either get disabled or can’t trigger action when the button is disabled.
Mastering the art of the disabled attribute
Sure, you can just drop disabled
and call it a day, but the world of disablement is vast:
- Conditional disablement: disable button based on validation:
- Toggle interaction for shifty conditions:
- When using frameworks like React, tie the disabled status with the component's state:
Unleashing the full power of button disablement
When disabling buttons, keep these pro-level tips stashed in your toolbelt:
- In jQuery,
.prop()
is the chosen one for disabling..attr()
is the misfit here. - For visually-disabled
<div>
elements, use.disabled
class, but it carries no power to actually disable interaction:
- Gild the button with CSS styles for
[disabled]
and.disabled
to maintain a consistent look.
Was this article helpful?