🌐 AI搜索 & 代理 主页
Skip to content

You cannot programmatically focus an element after you have attempted to focus it while it was hidden (display:none) #4950

@JoolsCaesar

Description

@JoolsCaesar

Description

Possibly related to #4867, I have replicated this in version 3.5.1 and 3.6. The linked example below uses 3.6. I haven't tested Firefox, but both Chrome and Edge display this issue.

See the following example. There's a focusable div at the top, which has a handler to report (at the bottom of the example) the number of times it is focused. When you click the div, it is only ever focused programmatically, because a handler calls preventDefault() on the mousedown.

There is a button to toggle the visibility (display) of the focusable element, but before showing the element, it attempts to programmatically focus it.

Focusing a display:none element is not expected to work, but the issue is what follows.

Once the element is shown, no future attempt to focus the element will work.

HTML:

  <div id="hideable">
    <div id="focusable" tabindex="1">
      I am focusable
    </div>
  </div>
  <button id="button">
    Toggle visibility
  </button>
  <div id="output">
    Click "I am focusable" to focus. Click "Toggle visibility" to hide/show the focusable element
  </div>

JS:

const $button = $('#button');
const $focusable = $('#focusable');
const $hideable = $('#hideable');
const $output = $('#output');

let focusinCount = 0;
$hideable.on('focusin', function() {
  focusinCount++;
  $output.text('I felt that ' + focusinCount);
});

let visible = true;
$button.click(function() {
  if (visible) {
    $hideable.hide();
  } else {
    $focusable.focus(); // Comment out this to fix
    $hideable.show();
  }
  visible = !visible;
});

$focusable.on('mousedown', function(event) {
  event.preventDefault();
  $focusable.focus();
})

Link to test case

https://jsfiddle.net/JoolsCaesar/2o089jga/

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions