Sometimes I use anchors styled as buttons and sometimes I just use buttons. I want to disable specific clicky-things so that:
- They look disabled
- They stop being clicked
How can I do this?
csshtmljquerytwitter-bootstrap
Sometimes I use anchors styled as buttons and sometimes I just use buttons. I want to disable specific clicky-things so that:
How can I do this?
Best Answer
Buttons
Buttons are simple to disable as
disabled
is a button property which is handled by the browser:To disable these with a custom jQuery function, you'd simply make use of
fn.extend()
:JSFiddle disabled button and input demo.
Otherwise you'd make use of jQuery's
prop()
method:Anchor Tags
It's worth noting that
disabled
isn't a valid property for anchor tags. For this reason, Bootstrap uses the following styling on its.btn
elements:Note how the
[disabled]
property is targeted as well as a.disabled
class. The.disabled
class is what is needed to make an anchor tag appear disabled.Of course, this will not prevent links from functioning when clicked. The above link will take us to http://example.com. To prevent this, we can add in a simple piece of jQuery code to target anchor tags with the
disabled
class to callevent.preventDefault()
:We can toggle the
disabled
class by usingtoggleClass()
:JSFiddle disabled link demo.
Combined
We can then extend the previous disable function made above to check the type of element we're attempting to disable using
is()
. This way we cantoggleClass()
if it isn't aninput
orbutton
element, or toggle thedisabled
property if it is:Full combined JSFiddle demo.
It's worth further noting that the above function will also work on all input types.