No outline on mouse focus but still have outline on keyboard focus?

css, html, javascript, jquery

Solution

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.

Problem

When elements of a page have focus (such as a link or button), they show an outline. I would like this outline to only display when that element was given focus by the keyboard, not by the mouse. Is it possible to determine how that element got its focus with JavaScript? If so, how do I then control the browser's own outlining feature?

Original source