Set focus on disabled button programatically not working
Solution 1
No, the button cannot receive focus because it is disabled. According to the W3.org specification (HTML5 version) disabled form controls must prevent click events and other interaction.
What you would need to do is enable the control at some point and assign focus that way. Another suggestion would be to leave the button enabled and implement some form of detection to determine whether or not to respond to the discard button's click
event.
Also, (and I'm taking a guess here) the save button likely shows as active because it was active before it was disabled. Although the browsers need to prevent access to a disabled item though interaction, removing the focus (or document.activeElement
in this case) may not be an implementation requirement of the specification.
Solution 2
Sorry to join the party late, but you can use aria-disabled
attribute instead of disabled
, and your element will be able to be assigned focus (even in IE and mobile, usually this problem doesn't rise in Chrome or Edge).
As a side note, if you also want your element to be navigable with keyboard TAB, of course make sure to set tabindex="0"
(however this is not needed for programmatically assign focus via JavaScript).
elemjay19
4 years as a front end developer, 1.5 years as a manager, 1 year as a product manager. I like problem solving and organization.
Updated on June 19, 2022Comments
-
elemjay19 almost 2 years
$(function () { $('#save').click(function() { $('#save').attr('disabled', 'disabled'); console.log($(document.activeElement).attr('id')); }); $('#test').focus(); console.log($(document.activeElement).attr('id')); });
button:focus { outline: 1px dotted #000000; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <body id="body"> <button id="discard" disabled="disabled">Discard</button> <button id="save">Save</button> </body>
I have a
Discard Changes
button, and when clicked, the user sees a confirmation dialog that says "Are you sure you want to discard your changes?". When they clickOK
, we close the dialog and want to put focus back on theDiscard Changes
button, but we've disabled it now because there are no changes to discard. When I check thedocument.activeElement
value, it's not the disabled button, it's the body element. However, when a user clicks theSave
button, since they're physically setting focus on the element, it gets the focus so even after it's disabled, it has focus. For some reason in the snippet I'm not seeing my focus style set on the disabled Save button even though in my app I do see it.Is it possible to set focus on a disabled button using jQuery? If not, why not? If so, what am I doing wrong?
-
dbc almost 3 yearsHow does this differ from the answer from mlr: you can use
aria-disabled
attribute instead ofdisabled
, and your element will be able to be assigned focus? -
Solrac almost 3 yearsThis answer was already stated and well explained.