Hi,

I have an input element on a form. When I open a popup form and then close it, I try to put the focus back on my input element by using the focus() method. However, that fails and it doesn't get focus.
When I press tab to get out of this input element, it takes several tries for it to get the tab event (since it wasn't focused, but how come it suddenly gets focus to respond later?)

Does anybody know how to get around that?

Thanks,
Sharon

Dani AI

Generated

described focus() failing after closing a popup; was right that the fix is about calling focus at the right time, and correctly asked how the popup is created — the solution depends on that. Common causes are: focus is requested before the browser has finished closing/hiding the popup, the element is not focusable (hidden/disabled/no tabindex), or the call happens in the wrong window. The MDN notes for [HTMLElement.focus()] explain that focus can be ignored in some situations. (See link below.)

For an in-page overlay/modal (a div or jQuery UI dialog) the close handler should restore focus after the UI is removed — letting the browser finish layout first usually fixes it. Example:

function closeOverlay() {
  overlay.style.display = 'none';
  setTimeout(function() {
    var el = document.getElementById('targetInput');
    if (el && typeof el.focus === 'function') {
      el.focus();
      if (el.select) el.select();
    }
  }, 0);
}

For a separate popup window opened with window.open, the parent can poll for popup.closed or the popup can call back into the opener before closing (watch for cross-origin restrictions). Example polling from the opener:

var popup = window.open('popup.html','p','width=400,height=300');
var t = setInterval(function() {
  if (!popup || popup.closed) {
    clearInterval(t);
    window.focus(); // may be ignored by some browsers
    document.getElementById('targetInput').focus();
  }
}, 200);

Additional checks: ensure the target element is visible, enabled, and focusable (add a tabindex if needed); call select() on text inputs to show the caret; avoid calling focus while the window is not active (browsers may ignore it). For details on popup behavior see MDN [Window.open()].

Recommended Answers

All 2 Replies

Do you know callback in JavaScript? Using callbacks you can popup a form and after it focusing on a particular element. Callbacks are functions executed after performing a particular operation.

Make me think how do you open a new popup for your new window?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.