Is it possible to detect when focus occurs outside an element without relying on global selectors like $(document)
, $(body)
, or $(window)
for performance reasons?
- If achieving this without global selectors is not feasible, provide a provable reason explaining why. It's crucial for me to understand the limitations of today's techniques.
- Bonus Round: Identify the most efficient selector(s)/event handler(s)/plugin(s) for this task in terms of computation time.
View my implementation featuring a simple HTML navigation bar with native keyboard navigation between anchor tags. The goal is to display a dropdown menu when focusing on inner anchor elements and hide it when not focused.
<ul class="test">
<li>
<a href="#">Title</a>
</li>
<li>
<ul>
<li>
<a href="#">Some link</a>
</li>
<li>
<a href="#">Some link</a>
</li>
<li>
<a href="#">Some link</a>
</li>
<li>
<a href="#">Some link</a>
</li>
</ul>
</li>
</ul>
The objectives are:
- Navigate between anchors using keyboard tab or shift+tab.
- Show the drop-down menu when focusing on inner anchors.
- Hide the drop-down menu when the focus is outside any inner anchors.
I have achieved 1 and 2, but 3 presents a challenge due to the limitations mentioned earlier. While using a global selector would make this task easy, I am exploring alternative solutions.
$(document).ready(function() {
dropdownMenu = $(".test > ul");
dropdownMenu.hide();
$(".test").focusin(function() {
if (dropdownMenu.is(":hidden")) {
dropdownMenu.show();
}
});
// Need a selector/event to handle focus/clicks outside $(".test") element
});
Note: I am cautious about using event.stopPropagation();
as described in CSS Tricks - The Dangers of Stopping Event Propagation. However, I am willing to consider it if it proves to be the most efficient approach.