0
$('#spell-check').on('click', 'li', function() { 
  $(this).focus()
});

<ul id="spell-check">
  <li tabindex="1">suggestion 2</li>
  <li tabindex="2">suggestion 1</li>
</ul>

The <li>'s are added dynamically to this list, but the <ul id="spell-check"> is included on load. The problem is that the <li> will not focus after it is clicked. What am I doing wrong please?

This is an edit I have just discovered that the issue is that I didn't have any css applied for the focus like:

#spell-check li:focus {
  border: 1px solid blue;
}

But what I can't understand is why when the li is focused did the chrome browser styling not apply on this occasion? Because when I focussed the same element based on a keystroke event it did apply the chrome blue border without adding the :focus css?

So the (standard Chrome) focused blue border was applied when I did:

$('input').on('keyup', function(e) {
   var $spellSuggestList = $("#spell-check");
   if (e.keyCode == 40) {
     $("li:first-child", $spellSuggestList).focus();
     return
   }
})

Anyway, I don't know if it's appropriate, but it might help someone else one day.

Platoscave
  • 139
  • 1
  • 7
  • Provide a minimum, working example that demonstrates your issue. – Ouroborus Jun 25 '22 at 03:08
  • Does this answer your question? [Why \`div:focus does\` not works without tabindex](https://stackoverflow.com/questions/49981814/why-divfocus-does-not-works-without-tabindex) – kmoser Jun 25 '22 at 03:25
  • *"Because when I focussed the same element based on a keystroke event it did apply the chrome blue border without adding the :focus css?"* Does this do something different than what I thoght it did? `$("li:first-child", $spellSuggestList).focus();` – zer00ne Jun 25 '22 at 06:11

1 Answers1

0

You need to add a tabindex attribute to the dynamically created <li>. Working example:

$('#spell-check').on('click', 'li', function() { 
  $(this).focus()
});
$('#spell-check').append('<li tabindex="-1">foobar</li>')
:focus {
    border: 1px solid red;
}
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

<ul id="spell-check">
  <li tabindex="1">suggestion 2</li>
  <li tabindex="2">suggestion 1</li>
</ul>

Reference: Why `div:focus does` not works without tabindex

kmoser
  • 8,780
  • 3
  • 24
  • 40