I have a situation where I want to be able to detach some input elements (including the element with focus) and reappend them elsewhere. This will inevitably cause focus to be lost in those elements. In Chrome I am able to set focus back in the input element using .focus(). In IE I can't. After calling focus() in IE the document.activeElement is the input control... and $(':focus') also says the input control has focus... but any new text typed into the control does not show up. It seems in Chrome that 'blur' is called automatically on detach(). In IE it is not.
Calling blur() directly on the input element with focus before the detach() causes blur() to be called twice on that element in IE... but only once in Chrome. This will allow me to call .focus(). The following JSFiddle illustrates this.
<div>
<input id="a" type='text' placeholder="detach, append, focus"/>
<input id="b" type='text' placeholder="blur, detach, append, focus"/>
</div>
<textarea id="log" cols="50" rows="20"></textarea>
<button id="clear">Clear all</button>
$(document).ready(function () {
var log = function(message) {
$('#log').val($('#log').val() + message + "\n");
}
// detach input on keyup, then reappend it and set focus on it.
// This doesn't set focus correctly in IE
$('#a').keyup(function () {
var inputA = $('#a');
var parent = inputA.parent();
var children = parent.children();
children.detach();
parent.append(children);
inputA.focus();
});
/// blur, then detach input on keyup, then reappend it, then focus it.
// Works correctly in IE
$('#b').keyup(function () {
var inputB = $('#b');
inputB.blur();
var parent = inputB.parent();
var children = parent.children().detach();
parent.append(children);
inputB.focus();
});
/// log blur events
$('#a').blur(function () {
log("a - blur");
});
$('#b').blur(function () {
log("b - blur");
});
// clear everything
$('#clear').click(function () {
$('#log').val("");
$('#a').val("");
$('#b').val("");
});
});
Note: This is not my actual scenario, it just illustrates the issue of detaching and then attempting to set focus back after append.
Is there a better way to be moving these elements so that focus is maintained consistently across browsers?
Unfortunately Microsoft refuses to fix this in Internet Explorer 11 and prior. You will be lucky if Edge reacts properly, and of course forcing all your users to upgrade will be fun...