Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE click on child does not focus parent, parent has tabindex=0

EDIT: See my own answer below: https://stackoverflow.com/a/25953721/674863

Demo: http://jsfiddle.net/fergal_doyle/anXM3/1/

I have a div with tabindex=0, and a child div with a fixed width. When I click on the child div I expect the outer div to recieve focus. This works fine with Firefox and Chrome, and only works with Internet Explorer (7 to 10) when the child div has no width applied.

With a width, clicking the child (white) div does not give focus to the outer one, and if the outer one previously had focus, clicking the child causes the outer to blur, which is a pain for what I want to do.

HTML:

<div tabindex="0" id="test">
    <div>Click</div>
</div> 

CSS:

div {
    border:1px solid #000;
    padding:20px;
    background-color:red;
}
div div {
    padding:8px;
    background-color:#FFF;
    cursor:default;
    width:200px;
}

JS:

var $div = $("#test"),
    $inner = $("#test > div");

$div.on("blur", function (e) {
    console.log("blur");
})
    .on("focus", function (e) {
    console.log("focus")
});
like image 906
Fergal Avatar asked Aug 15 '13 19:08

Fergal


2 Answers

Intercepting events and using JS to set focus ended up causing more problems.

I eventually figured out that using "normal" tags like divs or spans makes IE behave incorrectly. But use something like var or any custom tag and IE starts to behave like a proper browser.

See updated example: http://jsfiddle.net/fergal_doyle/anXM3/16/

HTML:

<div tabindex="0" id="test">
     <var class="iesux">Works</var>
     <foo class="iesux">Works</foo>
     <div class="iesux">Doesn't work in IE</div>
     <span class="iesux">Doesn't work in IE</span>
</div>

CSS:

div {
     border:1px solid #000;
     padding:20px;
     background-color:red;
}
.iesux {
     border:1px solid #000;
     display:block;
     padding:8px;
     background-color:#FFF;
     cursor:default;
     width:200px;
}

JS:

document.createElement("foo");

var $div = $("#test");

$div.on("blur", function (e) {
     console.log("blur");
})
     .on("focus", function (e) {
     console.log("focus")
});
like image 61
Fergal Avatar answered Nov 14 '22 12:11

Fergal


Have you tried to add :

$inner.click(function() {
  $div.focus();
});

and to prevent the outer div to blur after a focus use e.stopPropagation()

UPDATE: Since the click event fires after the blur I used the Mousedown event, because it fires before blur.

PS: Don't forget to handle keyboard events keydown if you want also to catch blurs fired by the keyboard.

http://jsfiddle.net/ouadie/x4nAX/

like image 38
Ouadie Avatar answered Nov 14 '22 14:11

Ouadie