Explain Codes LogoExplain Codes Logo

Best way to disable button in Twitter's Bootstrap

javascript
event-listeners
accessibility-attributes
conditional-disablement
Nikita BarsukovbyNikita Barsukov·Jan 30, 2025
TLDR

Immediately disable a Bootstrap button by setting its disabled attribute. In JavaScript, toggle the button's disabled property to true.

Example in JavaScript:

// Nothing to click here, move along document.querySelector('.btn').disabled = true;

In HTML, simply add disabled:

<!-- This button's on a break --> <button class="btn" disabled>Disabled Button</button>

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:

let anchorButton = document.querySelector('.btn-link'); anchorButton.classList.add('disabled'); //[Laughs maniacally] You shall not pass! anchorButton.addEventListener('click', function(event) { event.preventDefault(); });

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:

  1. Test all supported browsers.
  2. Update accessibility attributes such as aria-disabled.
  3. For <input> elements, use .prop('disabled', true) or disabled attribute. It's the same game, new player.
  4. 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:
// The button will behave. Eventually. function updateButtonState(button, isValid) { button.disabled = !isValid; }
  • Toggle interaction for shifty conditions:
// Back in action! document.querySelector('.btn').disabled = false;
  • When using frameworks like React, tie the disabled status with the component's state:
// This button listens to the state, like a good component <button disabled={this.state.isButtonDisabled}>Click me</button>

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:
// All show, no work. This one's just lazy document.querySelector('.btn').classList.add('btn-disabled');
  • Gild the button with CSS styles for [disabled] and .disabled to maintain a consistent look.