Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to make disabled button look disabled with jQuery

When I use .prop('disabled',true) to disable a button, it works, but the button does not look disabled. I remember in the old days when I used .attr('disabled','disabled') to disable buttons, they would become more visibly disabled, i.e. the text would be greyed out or something so the user wouldn't try to click. Now I think the button border fades a bit but the text is not.

What's the easiest way to get the old behavior back? I am lazy and don't want to write one line of code to disable the button and another to make it look disabled - I want to get both effects in a single command if possible. Should I use a different element other than a button? A different method of disabling?

I made a fiddle here: http://jsfiddle.net/ak2MG/. Here's the code.

HTML:

<button type='button' id='mybutton'>Click Me</button>
<div id="mydiv"></div>

Javascript:

$('#mybutton').click( function() {
    $('#mydiv').append("<p>Button was clicked.</p>");
    $('#mybutton').prop('disabled',true); } );
like image 247
baixiwei Avatar asked Mar 25 '14 21:03

baixiwei


2 Answers

it is pretty simple, just change the text style

$('#mybutton').click( function() {
    $('#mydiv').append("<p>Button was clicked.</p>");
    my_button_disable(this);
});

function my_button_disable(btn) {
    $(btn).prop('disabled',true);
    $(btn).css('color', 'lightgray');
    // put whatever else you want here
}

http://jsfiddle.net/ak2MG/6/

like image 177
robbmj Avatar answered Oct 12 '22 23:10

robbmj


Simplest - Add a state in CSS Target it with CSS to change the style, importantly the pointer-events: none will make it unresponsive. :

    button:disabled {
        background: #F5F5F5;
        color : #C3C3C3;
       cursor:none;
        pointer-events: none;
    }
like image 43
Greggo Avatar answered Oct 13 '22 00:10

Greggo