Web browsers utilize the CSS outline
property to indicate which element is currently in focus, a common knowledge amongst web developers. In jQuery, a typical implementation might look like this:
$(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 script listens for the mousedown
event on any given element. By using event delegation, it covers both existing and dynamically created elements. When an element is clicked with the mouse, its CSS outline
property is set to none
, effectively removing the outline.
The targeted element then receives a new handler for the blur
event. As soon as the focus leaves the element, the outline
property is reset to an empty string, allowing the browser to handle the outline display. Subsequently, the element removes its own blur
handler to optimize memory usage, ensuring that outlines are only visible when focused via keyboard navigation.
Edit
In response to feedback from Rakesh, a slight modification has been made to the function. It now checks if an outline
is already defined and avoids overriding it. Check out the demo here.