Reputation: 919
I have a dropdown with tabindex attribute.
When I click with the mouse on it using chrome, I get a blue outline around the dropdown.
If I cancel the "tabindex" attribute it doesn't happen, but I don't have a tabindex for this control.
If I cancel the outline using css:
*:focus
{
outline: none;
}
it works too, but I don't get the outline when moving with tabs (and have no indication that this control is focused).
Is there any way to make this outline show only when using "tab" and not on each mouse click?
Upvotes: 1
Views: 2988
Reputation: 3158
The easiest way I can think of is to write your own outline style. This can be easily applied to any element.
CSS:
.input {
border-radius:7px;
border:1px solid #ccc;
outline:none;
}
.focused {
border:1px solid #55d;
}
jQuery (because onfocus has notes about not working well in the MDN page):
$('input').focus(function () {
$(this).addClass('focused');
});
$('input').blur(function () {
$(this).removeClass("focused");
});
If you really really need it to not show up on clicks, you'll need something like this:
var clicked = false; //hold whether or not we have a click
$('input').click(function () { // if they click, flag it.
clicked = true;
$(this).removeClass('focused'); //remove the focus class in case it got set-see note.
setTimeout(function() { // remove the click flag after 1/5th of a second.
clicked = false;
}, 200);
});
$('input').focus(function () { // when it gets focused, handle it.
handle_it(this);
});
function handle_it(e){
setTimeout(function() { // wait a bit, then check for the flag.
if (clicked === false) { // they didn't click.
$(e).addClass('focused');
}
}, 150); // you may need to tweak this value. 150 was right for opera, see note
}
$('input').blur(function () { // remove the focus
$(this).removeClass("focused");
});
Note: focus
is applied before click
no matter where the handler is placed (at least, that's what I found in jQuery1.11). This means that you have to delay focus
if you want to have click applied first. 150ms was about right for opera, otherwise you get a flash of the focused style. This is why we remove the class in the click handler.
You can also use shadows and fades and all kinds of pretty stuff to make it pretty if you use this method.
Obviously you should use a more specific selector than 'input'
.
Fiddle: https://jsfiddle.net/gypvpvr7/1/
Upvotes: 2