Browsers use the CSS outline
property to show which element has the focus, as you might already know. So, in jQuery, you might use:
$(document).ready(function() {
$("body").on("mousedown", "*", function(e) {
if (($(this).is(":focus") || $(this).is(e.target)) && $(this).css("outline-style") == "none") {
$(this).css("outline", "none").on("blur", function() {
$(this).off("blur").css("outline", "");
});
}
});
});
Explanation: This function looks for the mousedown
event on any element. This event is delegated, meaning it will apply to elements currently on the page as well as any created dynamically in the future. When the mouse is clicked over the element, its CSS outline
property is set to none
; the outline is removed.
The targeted element gets a new handler for blur
. When focus is taken from the element, the outline
property is set to a blank string (this removes it from the element's style
attribute), allowing the browser to control the outline again. Then, the element removes its own blur
handler to free up memory. This way, an element is only outlined when focused from the keyboard.
Edit
Based on Rakesh's comments below, I made a slight change. The function can now detect if there's already an outline
set, and will avoid overriding it. Demo here.