Oleksii Bezuhlyi
Oleksii Bezuhlyi

Reputation: 43

Focusing using javascript doesn't show outline style for checkbox like it does when use Tab

When navigating through inputs on the page using tab, they become outlined once in focus. But when I try to do something similar using, for example, arrow keys, focusing on checkboxes doesn't show outline styles.

jq(elems).keydown(function(e){
    if(!e) return;
    if(e.keyCode == '38') {
        var el = ... // searching for the next element
        el.focus();
    }

Even if I manually add outline styles after focus, or add css like

input[type="checkbox"]:focus 
{
  outline-style:auto; 
  outline-color: 
 -webkit-focus-ring-color;
}

it wouldn't work. The focus is on the checkbox, the styles are there, but they are not displayed. Some other styles applied correctly, for example if I add styles like:

input[type="checkbox"]:focus {
    box-shadow:1px 1px lightgrey;
}

I can see shadow box when focus is on the checkbox, but outline is not there.

Upvotes: 3

Views: 1189

Answers (1)

joshdoescode
joshdoescode

Reputation: 59

I've only done this in raw js, but hopefully it helps:

Make sure to set the event listener on the document - otherwise you're only firing the event if the key is pressed whilst already 'inside' the element.

JS:

var el = document.getElementById('my-check');
document.addEventListener('keydown', function(e) {
  e.preventDefault();
  el.focus();
});

CSS:

input[type="checkbox"]:focus, input[type="checkbox"]:active {
  width: 100px;
  height: 100px;
  outline-color: -webkit-focus-ring-color;
  outline-style: solid !important;
}

DOM:

<form>
  <input type="checkbox" id="my-check" />
</form>

Fiddle: https://jsfiddle.net/radmpxgs/1/

Sorry for the edits.

Upvotes: 1

Related Questions