Identifying the moment when attention shifts away from an element

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:

  1. Navigate between anchors using keyboard tab or shift+tab.
  2. Show the drop-down menu when focusing on inner anchors.
  3. 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.

Answer №1

It seems like I might not have fully grasped the question, but I believe I understand what you're asking.

To achieve this, you can utilize the event.target in conjunction with the closest method within the context of the focusin event.

$(document).on('focusin', function (event) {
  var $target = $(event.target);
  if (!$target.closest('.bar').length) {
    console.log('You have focused outside of the .bar element!');
  }
});

You can also find a working example on JSFiddle: https://jsfiddle.net/crswll/qk14r7c7/2/

Answer №2

If you want a solution without using global selectors, consider adding a delay to the closing action:

  var isVisible = false;

  $(".selector").focusin(function() {
    if (menu.is(":hidden")) {
      menu.show();
    }
    isVisible = true;
  });

  $(".selector").focusout(function() {
    isVisible = false;
    setTimeout(function() {
      if (!isVisible && menu.is(":visible")) {
        menu.hide();
      }
    }, 100);
  });

This may seem complicated, but it helps prevent accidental closures while navigating through tabs. Check out https://jsfiddle.net/abc123/3/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Including file format extension in the absence of one

I have created a script that loops through every image source on the page, extracting the extension. If the extension is not recognized or does not exist, I automatically add .jpg to the end. Strangely, the if statement always evaluates to true no matter ...

Angular ngClass and ngIf directives failing to update upon alterations

In my current Angular project, I am working on a functionality where I need to dynamically change a class based on a variable without having to refresh the page. I have experimented with *ngIf/else and [ngClass] directives, which do work, but unfortunatel ...

Actions for HTML form submission to API through proxy link

Currently, the form is functioning properly with this setup <form method="POST" action='http://localhost:3000/newRecord'> However, my goal is to simplify the action attribute to just be action='/newRecord'. In React, I achieve ...

Using the selector gadget to scrape websites with R programming

Attempting to extract information from the site: Encountered a few obstacles: Initially used the selector gadget to identify tables, but it was not effective. Simply typing "table" highlighted 9 tables. Upon running the following code: html <- read_h ...

Using NGRX Effects to Load Data for a Specific Item in Angular

On my website, there is a page that displays a range of products from the store managed by a reducer called products. When an action PRODUCTS.LOAD_ALL is dispatched, it triggers an API call through an effect and then sends a PRODUCTS.LOAD_ALL_SUCCESS actio ...

Guide on transforming an array object for compatibility with MUI's Autocomplete field

I've encountered a challenge while attempting to transform my incoming object into a format suitable for MUI's Autocomplete component. Here is the current code snippet I am working with: const [contactList, setContactList] = useState([]); useEf ...

What is the best way to trigger an AJAX function every 15 seconds?

As part of my web application, I have implemented a JavaScript function that is triggered by the <body onload> event. Within this function, there is a while loop that continuously iterates until it receives the desired response from a PHP page. Unfo ...

Navigating with React Router using URL parameters

After implementing react router with a route path taskSupport/:advertiserId that includes parameters, I encountered an issue when trying to access the link http://localhost:8080/taskSupport/advertiserId. My browser kept returning 404 (Not found) errors for ...

Just delving into React for the first time and encountering undefined values in PropTypes

I am completely new to React and attempting to create a basic weather application in order to understand how components interact with each other. I have a forecast.json file that contains information such as temperature, date, humidity, wind speed, wind di ...

If I desire to utilize a particular font that I am aware is not readily accessible on the majority of users' computers

Is it possible to embed a specific font into my website if I know it's not commonly available on users' computers? I've seen some websites using unique fonts as text and not images, so I'm curious about how that is achieved. Thank you, ...

Why is the image auto-swapping script failing to display images frequently?

I have a script that is currently running to rotate between two different logos on my webpage. What I am attempting to achieve is for the page to load and then seamlessly transition from one image to the other without any blank space. Below is the code I ...

C# - Issue with Webbrowser failing to fully load pages

I am facing an issue with loading pages completely on the web browser, likely due to heavy usage of JavaScript. To address this problem, I have integrated another browser into the project called Awesomium. I am wondering if Awesomium supports using getEle ...

Regular expression for identifying a specific attribute paired with its corresponding value in a JSON object

Below is a JSON structure that I am working with: 'use strict'; // some comment is going to be here module.exports = { property1: 'value1', property2: 999, }; I am looking to remove the property2: 999, from the JSON. I attempted ...

Sorting data values based on real-time dropdown menu selections

Currently, my view class displays a table populated with data from the backend using the MVC framework in CodeIgniter. I have also added dropdown menus above each column that display the same records from the database. My goal is to enable users to filter ...

What is the best way to display these images correctly within a slider?

My goal is to display 4 images/company logos per slide, but they all end up clustered on one slide. Despite my efforts to adjust the CSS, nothing seems to work. This is what my code currently renders: Here are the react component codes I am using: To se ...

Ways to specifically load a script for Firefox browsers

How can I load a script file specifically for FireFox? For example: <script src="js/script.js"></script> <script src="js/scriptFF.js"></script> - is this only for Firefox?? UPDATE This is how I did it: <script> if($. ...

The native javascript modal fails to appear

I'm attempting to implement the functionality from this Codepen demo into my project. I've copied over the HTML, CSS, and JavaScript code: <!DOCTYPE HTML> <html> <head> <script> var dialog = docume ...

An absence of data causes the function to malfunction

One of the components in my application is responsible for rendering select elements on the screen, allowing users to dynamically order data. The initial state is as follows: state = { sortBy: [ { author: 'asc' } ] }; In this s ...

The image is not displaying on the page

Slider Section (Gray Part) We verified after loading, and the data was spot on. In development mode (F12), we can inspect object information (ImgURL, Text, etc.). However, it is not being displayed. Below is the template code and script code. Thank you. ...

Deciding between Bull queue and Database Triggers

My current project requires creating records in the database for users on a recurring basis, such as every Monday weekly or biweekly. I have identified two potential solutions to achieve this goal. One option is to utilize Database Triggers to generate ...