Capture any clicks that fall outside of the specified set

I am facing an issue with my navigation drop down menu. Currently, the pure CSS functionality requires users to click the link again to close the sub-menu.

What I want is for the sub-menu to close whenever a click occurs outside of it.

I attempted a solution using JavaScript, but it didn't work as expected:

$('*:not(.submenu > li > a)').click(function() {
    $('nav .dropdown input').removeAttr('checked');
    console.log('clicked outside sub-menu');
});

This code captures every click event, including those within .submenu > li > a, causing the menu to close even when trying to open it.

The dropdown menu is controlled by a checkbox input in the CSS. Here's the CSS code for reference, although my issue lies in the JavaScript part:

Here is a fiddle containing the CSS code: https://jsfiddle.net/z3yj7pLs/

ul.dropdown {
    position:fixed;
    top:30px;
    width:100%;
    height:3em;
    margin:0;
    padding:0 10px;
    color:#eee;
}

(remaining CSS properties remain unchanged...)

Answer №1

If you want to detect clicks on the document and determine if the click occurred outside of the dropdown, you can use the following code:

$(document).click(function(event) {
    if ($(event.toElement).parents('.dropdown').length > 0) {
        console.log('Clicked inside the dropdown area');
    } else {
        console.log('Clicked outside the dropdown area');
    }
});

Check out this functional snippet:

$(document).click(function(event) {
    if ($(event.toElement).parents('.dropdown').length > 0) {
     console.log('Clicked inside the dropdown area');
    } else {
        console.log('Clicked outside the dropdown area');
    }
});
body {
  background: black;
}
ul.dropdown {
  position: fixed;
  top: 30px;
  width: 100%;
  height: 3em;
  margin: 0;
  padding: 0 10px;
  color: #eee;
}

/* More CSS code... */

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown">
  <li>
    <input id="nav-dropdown-check" type="checkbox" name="menu" />
    <label for="nav-dropdown-check"><a class="nav-imitation">More</a></label>
    <ul class="submenu">
      <li><a href="#">Submenu 1</a></li>
      <li><a href="#">Submenu 2</a></li>
    </ul>
  </li>
</ul>

Answer №2

To optimize this task, consider implementing event delegation:

$('body').on('click', ':not(.submenu > li > a)', function() {
    $('nav .dropdown input').removeAttr('checked');
    console.log('clicked outside sub-menu');
});

By utilizing event delegation, you can avoid cluttering the DOM with numerous event handlers. Instead, you only need one handler that disregards clicks on your menu. You may have to refine the ':not()' selector or apply JavaScript logic within the event handler (e.g.

if (!$(this).parents('.submenu').length) { ...collapse }
)

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

Looking to transfer JSON data between JavaScript and Java code

I am dealing with a JSON string within my JavaScript code and I want to pass this information to a Java class. Can I simply use a regular Java class for this task or is it necessary to implement a servlet? Furthermore, I am curious about the process of pa ...

Google Chrome introduces innovative composite layers to handle stubborn content resistant to compression

I'm trying to understand the meaning behind the message in the Chrome profiler that says "Layer was separately composited because it could not be squashed." Recently, while modifying my HTML, I added a fixed position div inside a relative div and app ...

When an Ajax call is made, the controller will return a HTTP status code of 500 if it queries the database without using the `

I recently developed a Google Maps page for a client with a custom draw search feature where users can draw a polygon to find locations within that area. During testing on localhost, everything functioned perfectly. However, upon completing the polygon a ...

Knockout Table Sorter not refreshing data on update

I'm currently working on a code that updates a table every 5 seconds. I have implemented a table sorter with Knockout.js, however I am facing an issue where the data is being appended to previous data instead of updating it. Below is the code snippe ...

Is the combination of elements by CSS Minifiers harmful?

Recently, I came across an interesting CSS minifier tool at . On that webpage, there is a section titled "What does the CSS Compressor purposely NOT do?" which highlights four specific things, two of which caught my attention due to their potential impact: ...

React issue: parent state becoming unresponsive when updating during input onChange event

I am currently working on a large form that consists of at least 50 input fields. I have developed a function within the form component to store the input values in the form's state: PARENT FUNCTION saveToState(details) { const { company } = thi ...

React fails to display the content

Starting my React journey with Webpack configuration. Followed all steps meticulously. No error messages in console or browser, but the desired h1 element is not showing up. Aware that React version is 18, yet working with version 17. App.jsx import Reac ...

The most effective way to code overlapping html buttons

Can you help me figure out how to make clickable areas on my HTML5 web page without them overlapping? Here's what I'm trying to do: I want the red, blue, and green areas to be clickable links, but not overlap. For example, when clicking on the f ...

Utilize React Helmet for Dynamic Page Titles

Currently, I am utilizing Gatsby with react-helmet to manage the title and meta tags in the head of my website. However, I am eager to find a way to also display this title in the actual text of the page through a global <Header /> component. In proj ...

Upload the PDF file along with other form data in a React application

I'm currently facing an issue with using formData for submitting a pdf file const [file,setFile] = useState() const [isFilePicked, setIsFilePicked] = useState(false); I have an input of type file <input accept=".pdf" type="file&quo ...

What happens when the user closes a notification in GetUIkIt 3?

Is there a way to detect when a UIKit notification has been closed? The UIkit notification plugin () mentions that it has a close event. Can this be utilized for notifications triggered programmatically as shown below? e.g. UIkit.notification({ mess ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

retrieving data from a node and embedding it into an HTML file

In my project, I have an index.html file and an app.js nodejs file. Within the app.js file, there is a variable named "name" that I would like to display in my index.html page. Here is the code snippet: var name = "Utsav"; var HTTP = require('HTTP&a ...

Create a form with Vue that generates input fields based on JSON data and

I am seeking assistance with implementing a truncate filter for vueformulate in my project. I am generating the form from json data and need to limit the label to 80 characters, with a read more/less option. The data is dynamic, so changing the label in th ...

Iterating over images and displaying them in Laravel's blade templating engine, updating outdated Angular code

Currently, I am in the process of transitioning an Angular repeat function used for displaying images on our website (built with Laravel). The goal is to eliminate Angular completely and handle everything using Laravel loops in the blade template. I have ...

Issue: jQuery Datatable not functioning properly while attempting to populate the table through JavaScript.Explanation: The

I'm currently working on populating a table using JavaScript. However, I've encountered an issue where the table is being populated but it shows "No data available in table". Furthermore, when I try to interact with the data, it disappears. This ...

"The powerful trio of Moongose, expressjs, and node-webkit combine forces

I'm currently in the process of developing an app using node-webkit, with expressjs and mongoose as the foundation. As a newcomer to this technology stack, I've encountered some challenges. One specific issue involves my attempt to integrate a m ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

What is the best way to integrate my company's global styles CDN for development purposes into a Vue cli project using Webpack?

After attempting to import through the entry file (main.js)... import Vue from 'vue' import App from '@/App' import router from '@/router/router' import store from '@/store/store' import BootstrapVue from 'boot ...

<datalist> trigger that occurs when a selection is made

I'm currently working on a feature that resembles autocomplete, and instead of creating my own dropdown, I have decided to experiment with the use of < datalist >. I appreciate using native elements as they are compatible across various devices, ...