blindworld
blindworld

Reputation: 121

IE focus event randomly fails after ajax load

Currently, we're only supporting IE8.

I have an ajax call that gets data from the server, replaces the HTML in a container div with the response, then attempts to focus's in on an element contained in the response.

Depending on [IE Magic]? sometimes this code works, sometimes it doesn't. I need to find something that can work 100% of the time. The console.log statement logs the correct ID 100% of the time, even when the focus fails.

$.ajax({
    type: 'POST',
    url: that.Url,
    contentType: 'application/json; charset=utf-8',
    dataType: 'html',
    data: dataToSend,
    success: function (response) {
        $(container).html(response);
        that.initialize();

        var element = document.getElementById(elementId);
        setTimeout(function () {
            setTimeout(function () {
                setTimeout(function () {
                    setTimeout(function () {
                        setTimeout(function () {
                            setTimeout(function () {
                                console.log($(element).attr('id'));
                                element.focus();
                            }, 10);
                        }, 10);
                    }, 10);
                }, 10);
            }, 10);
        }, 10);
    }

The nested setTimeouts were there to see if maybe something else was being put on the stack during an earlier timeout. I tried it with a single setTimeout set to 1000, and was still seeing random failures. I've tried replacing $(container).html(response); with $(container)[0].innerHTML = response; and that still doesn't work consistently. I've tried replacing document.getElementById(element) with $(container).find('#' + elementId). I've also tried moving var element = document.getElementById(elementId); into the setTimeout and am still seeing random failures. Using Firefox, 0 of the setTimeouts are needed and the code runs flawlessly, however that's not an option for us unfortunately. Changing console.log to alert does fix the issue, but only because it delays the focus until after 'ok' is clicked but that extra mouse click is awful for usability.

that.initialize() adds classes to new elements, adds events, modifies the widths/heights of new elements, etc... and all of that works 100% of the time.

Upvotes: 2

Views: 905

Answers (2)

Jacob
Jacob

Reputation: 78860

This appears to be a true bug in older IEs. One trick that reportedly works is to call .focus() twice in a row.

Upvotes: 4

lbstr
lbstr

Reputation: 2832

Shouldn't it be $(element).focus() instead of element.focus()? focus is a jQuery method, which must be invoked on a jQuery object.

Upvotes: 1

Related Questions