Click outside to toggle dropdown and hide it

My dropdown menu is currently working, but I would like it to close when I click outside of it. I've tried various solutions provided in other posts, but I just can't seem to get it right. Can someone please help me figure out what I am missing? Thank you!

$("#toggle").on('click', function() {
   $(".dropdown").toggleClass("dropdown--visible");
});

$(document).click(function(){
    $(".dropdown").hide();
});

$(".dropdown").click(function(e){
    e.stopPropagation();
});
.dropdown {
  background: red;
  display: none;
}

.dropdown--visible {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="toggle">Toggle dropdown</button>

<div class="dropdown">
    <ul>
      <li>one</li>
      <li>two</li>
  </ul>
</div>

Answer №1

$("#toggle").on('blur click', function() {
   $(".dropdown").toggleClass("dropdown--visible");
});

$(document).click(function(){
    
});
.dropdown {
  background: red;
  display: none;
}

.dropdown--visible {
  display: block!important;
}
.dropdown--invisible {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="toggle">Toggle dropdown</button>

<div class="dropdown">
    <ul>
      <li>one</li>
      <li>two</li>
  </ul>
</div>

Answer №2

By setting up a click event listener for the entire document, it will respond every time you click anywhere on the page. To target specific elements like dropdowns, you can use a common class to filter out those events.

<button id="toggle" class="dd">Toggle dropdown</button>

<div class="dropdown dd">
  <ul>
    <li>one</li>
    <li>two</li>
  </ul>
</div>

$(document).click(function(e){
  if (!$(e.target).hasClass('dd')) {        
    $(".dropdown").removeClass("dropdown--visible");
  }
});

It is recommended to use removeClass() instead of hide(), as hide() directly applies a display:none; style which may be difficult to manage.

Answer №3

This solution features a vanilla-flavored approach using a handleDropdown function that evaluates two specific conditions:
- First, it checks if the toggle button was clicked.
- Secondly, it verifies if the dropdown is currently hidden.

If both conditions are met, the dropdown will be displayed. Otherwise, it will be hidden.

const dropdown = document.getElementsByClassName("dropdown")[0],
      toggle = document.getElementById("toggle");
document.addEventListener("click", handleDropdown);

function handleDropdown(event){
  if(event.target == toggle && dropdown.style.display != "block"){
    dropdown.style.display = "block";
  }
  else{
    dropdown.style.display = "none";
  }
}
.dropdown {
  background: red;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="toggle">Toggle dropdown</button>
<div class="dropdown">
  <ul>
    <li>one</li>
    <li>two</li>
  </ul>
</div>

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

Troubleshooting: Image Not Displaying in Twitter Bootstrap Theme

I'm new to using bootstrap and I'm encountering an issue where my image is not showing up. Strangely, the default background image is appearing even though I have not referenced it in the HTML or CSS files. View my code here ...

Tips for fixing the issue: Absence of the environment variable 'TWITTER_CONSUMER_KEY'

Being a novice in programming, I didn't anticipate encountering errors so soon. Today, I attempted to code a Node.js application for posting Twitter Feeds to Discord but faced failure. I'm puzzled as to why this error is occurring even though I& ...

Using AJAX to dynamically serialize data from a form and POST it in PHP

I have a script on jQuery and HTML5 that dynamically generates a form. Next, I utilize the following code: var OForm = $('#OForm'); // Find disabled inputs, and remove the "disabled" attribute var disabled = OForm.find(':input:disabled&ap ...

JavaScript inheritance through prototypes and the properties of objects

I am currently exploring the concept of prototyped inheritance in JavaScript for a function. This process is well documented in Wikipedia's javascript article. It functions smoothly when dealing with simple JavaScript types: function Person() { t ...

A problem arises when the React effect hook fails to trigger while utilizing React Context

I have created a component that is supposed to generate different pages (one for each child) and display only the selected page: import * as React from "react"; export interface SwitchProps { pageId: number; children: React.ReactChild[]; } ...

Error message: The module '@project-serum/anchor' does not export the object 'AnchorProvider' as intended

I encountered an issue while attempting to run my react application. The issue: Attempted import error: 'AnchorProvider' is not exported from '@project-serum/anchor'. The import declaration in my code: import idl from './idl.json ...

What could be the reason for the undefined return from .forEach method?

While I have come across several questions on this particular topic , none of them have been able to provide me with a solution. Let's take a look at the data I am working with: const testsMap = { 0: ["just", "test"], 1: ["b ...

spark of unique substance

Having trouble with cycle2 as all images are briefly displayed when the page loads. I tried the recommended solution http://jquery.malsup.com/cycle/faq.html but it didn't stop the flashing, indicating a different issue: The suggested fix for Cycle is ...

Result of a callback function

Having trouble returning a value for form validation using a callback function. It's not working for me... <form action="loggedin.php" onsubmit="return test(valid)" method="post"> function test(callback) { var k = ""; var httpRequest = ...

Use jQuery to redirect the user if the URL does not match

Is there a way to automatically redirect users to a specific page if they are not currently on that page? For example, something like the following pseudo code: if not (url = example.com/index.php) redirect to example.com/index.php /if When a user vi ...

Run the JavaScript configuration (Object) prior to converting it to JSON format

Is there a way to implement functions within a JavaScript file (configuration for backend server) that execute before parsing the data to JSON? For example: config.js module.exports = { structure_layout: { BUILDING: "BUILDING", FLOOR: ...

Aurelia-powered DataTable plugin for effortless data updating

I'm currently utilizing the DataTables and DatePicker plugins along with Aurelia in my project. The goal is for the user to select a date, which will then prompt the data table to display the corresponding data for that specific date. However, I' ...

creating a picture within a frame

the code : function DrawFirstRow() { Position = 1; width = 84; height = 84; startX = 28; startY = 28; for (index = 0; index < canvasWidth; index += 28) { /// use += ctx.drawImage(tankImage, (Position ...

Exploring timezones using moment.js

I have received scheduledTime and timezone data from an API, for example: scheduledTime: 1603890000000 timezone: "EDT" My goal is to display this information in the user's device timezone, such as CST. What would be the most effective approach to ach ...

“What could be causing the issue of newly added components not appearing on an extjs panel after removing other components?”

Using ExtJs 6 classic, I have a situation where I am dealing with an Ext.panel.Panel that contains dynamically created child Panels and containers. What I do is save references to these containers and remove them from the parent Panel (this) utilizing the ...

What is the best way to format a time in a 12-hour clock using JavaScript?

Is it possible to create a timer that performs an action after 12 hours? I want the timer to start at 6am and end at 6pm, lasting for exactly 12 hours. Additionally, I'm interested in converting my current 12-hour clock into a 24-hour format. I am se ...

Implementing a toggle function in Vue.js to add or remove a class from the body element when a

I'd like to add a toggleable class to either the body element or the root element("#app") when the button inside the header component is clicked. Header.vue : <template lang="html"> <header> <button class="navbar-toggler navbar-tog ...

MySQL database not reflecting changes made via ajax code

I have an issue with my ajax code, where it correctly displays errors and success messages on the page but fails to update the database when I click the submit button. The form includes a select dropdown menu that is populated with options from the databa ...

The element fails to receive the class when it is being clicked

Currently, I am in the process of developing a Joomla website and I am working on implementing an accordion feature for the category descriptions based on the placement of H3 headings in the WYSIWYG editor. Here is the basic function I have so far (althou ...

Learn the process of dynamically wrapping component content with HTML tags in Vue.js

Hey there! I'm looking to enclose the content of a component with a specific HTML tag, let's say button for this scenario. I have a function that dynamically returns a value which I use as a prop. Based on that, I want to wrap the component&apos ...