Javascript Function : Toggle visibility of div when user clicks anywhere on the page

I have implemented a feature where clicking on the 3 dots reveals a div, and clicking again hides it. However, I would like the div to hide when clicking anywhere else on the document.

Imagine two circles - clicking on one circle displays a div, while clicking on the other closes the current one and opens a related div. Yet, whenever I click elsewhere on the document, neither of the divs are closed.

$("#discussion_declined , #discussion_pending").click(function() {
  var relatedDiv = $(this).closest('.panel').find('.discussion_edit_div');
  relatedDiv.toggle("fast");
  $('.discussion_edit_div').not(relatedDiv).hide('fast');

});
.discussion_small_round_div {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  position: relative;
  background: #2d3446;
  bottom: 9px;
  left: 15px;
  float: right;
}
.discussion_small_round_div:after {
  content: '\2807';
  font-size: 1.5em;
  color: white;
  position: absolute;
  left: 9px;
  top: 1px;
}
.discussion_edit_div {
  background: #FFFFFF;
  display: none;
  position: absolute;
  right: 35px;
  border: thin #ced0d1 solid;
  z-index: 1001;
  width: 150px;
  box-shadow: 0px 3px 3px #ccc;
}
ul li {
  padding: 5px 15px;
  list-style-type: none;
  color: #838383;
}
ul li:hover {
  background: #eeeded;
  cursor: pointer;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


<div class="panel discussion_panel_div no_background no_box_shadow" style="position: relative;">
  <div class="panel-heading no_border_radius bg-dark set_padding_0">
    <div class="discussion_small_round_div pull-right cursor_pointer" id="discussion_declined"></div>
  </div>
  <div class="discussion_edit_div">
    <ul>
      <li> <span class="glyphicon glyphicon-trash"></span>&nbsp; Replicate</li>
      <li><span class="glyphicon glyphicon-trash"></span>&nbsp; Delete</li>
      <li><span class="glyphicon  glyphicon-ban-circle"></span>&nbsp; Deactivate</li>
    </ul>
  </div>
</div>


<div class="panel discussion_panel_div no_background no_box_shadow" style="position: relative;">
  <div class="panel-heading no_border_radius bg-dark set_padding_0">
    <div class="discussion_small_round_div pull-right cursor_pointer" id="discussion_pending"></div>
  </div>
  <div class="discussion_edit_div">
    <ul>
      <li> <span class="glyphicon glyphicon-trash"></span>&nbsp; Replicate</li>
      <li><span class="glyphicon glyphicon-trash"></span>&nbsp; Delete</li>
      <li><span class="glyphicon  glyphicon-ban-circle"></span>&nbsp; Deactivate</li>
    </ul>
  </div>
</div>

Answer №1

Although Praveen's solution is effective, it is possible to achieve the same outcome without modifying your HTML code.

To do this using jQuery, simply include the following:

$(window).click(function() {
//Hide any visible menus
$('.discussion_edit_div').hide('fast');
});

$("#discussion_declined , #discussion_pending").click(function(e) {
  e.stopPropagation();
  var relatedDiv = $(this).closest('.panel').find('.discussion_edit_div');
  relatedDiv.toggle("fast");
  $('.discussion_edit_div').not(relatedDiv).hide('fast');

});

With these adjustments, you'll be all set.

This method also allows for easier toggling between ul elements with just one click, unlike Praveen's approach which requires two clicks to open another ul.

See the demonstration here:https://jsfiddle.net/zfqqqr1c/1/

Answer №2

It's intriguing to see how Bootstrap tackles this issue. They utilize a mask that restricts clicks to either the mask itself or the menu items.

$(function () {
  $(".mask").hide();
  $("nav > ul > li > a").click(function () {
    $(this).closest("li").addClass("open");
    $(".mask").show();
    return false;
  });
  $(".mask").click(function () {
    $(this).hide();
    $(".open").removeClass("open");
  });
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none; line-height: 1; box-sizing: border-box;}
body {background-color: #f5f5f5;}
a {text-decoration: none; color: inherit;}

.mask {position: fixed; top: 0; bottom: 0; right: 0; left: 0; z-index: 8;}

nav > ul > li {display: inline-block; position: relative; width: 30%;}
nav > ul > li a {display: block; padding: 5px; border: 1px solid #ccc;}
nav > ul ul {position: absolute; left: 0; right: 0; z-index: 9; display: none;}
nav > ul > li.open > ul {display: block;}
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<div class="mask"></div>
<nav>
  <ul>
    <li>
      <a href="">Main Item 1</a>
      <ul>
        <li><a href="">Sub Item 1</a></li>
        <li><a href="">Sub Item 2</a></li>
        <li><a href="">Sub Item 3</a></li>
        <li><a href="">Sub Item 4</a></li>
        <li><a href="">Sub Item 5</a></li>
      </ul>
    </li>
    <li>
      <a href="">Main Item 2</a>
      <ul>
        <li><a href="">Sub Item 1</a></li>
        <li><a href="">Sub Item 2</a></li>
        <li><a href="">Sub Item 3</a></li>
        <li><a href="">Sub Item 4</a></li>
        <li><a href="">Sub Item 5</a></li>
      </ul>
    </li>
    <li>
      <a href="">Main Item 3</a>
      <ul>
        <li><a href="">Sub Item 1</a></li>
        <li><a href="">Sub Item 2</a></li>
        <li><a href="">Sub Item 3</a></li>
        <li><a href="">Sub Item 4</a></li>
        <li><a href="">Sub Item 5</a></li>
      </ul>
    </li>
  </ul>
</nav>

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

Guide on utilizing Subscribe Observable for performing lookup in Angular

I am new to Angular and seeking guidance as my approach may not be the best. Please advise me on a better solution if you have one. My goal is to display a list of records in table format, retrieved from the database where only Foreign Keys IDs are availa ...

When there is an absence of data, the jQuery datatable mysteriously van

I have encountered an issue in my Django app where a datatable used in the template disappears if there is missing data in any column or row. The problem occurs when trying to download the data in CSV, Excel, PDF, or copy format. Here is the HTML code snip ...

Combining shared table rows with embedded ruby code in Javascript - is it possible?

I'm a new Javascript learner and I'm attempting to create a function that will merge rows with the same value (year in this case) and add their numbers together. Although my code isn't functioning as expected, it also doesn't seem to be ...

Flexslider for Lazy Loading Images

Hello everyone, I'm working on implementing lazy loading for my flexslider slideshow on my website. However, I've encountered a problem where all the images load and appear on the site for a few seconds before the slider loads. I believe this is ...

POST request body is not defined

Client Interface: procedure OnButtonClick(Sender: TObject); begin gcm := GetGCMInstance; p := TJavaObjectArray<JString>.Create(1); p.Items[0] := StringToJString('460004329921'); FRegistrationID := JStringToString(gcm.register(p)); ...

What is the best way to transfer a JavaScript variable value from an HTML page to a Model variable within the controller?

I'm facing a challenge in my HTML page where I need to pass a variable value from the frontend to a Model class in an MVC project. What is the most efficient way to achieve this with minimal code? Here's what I have attempted: Index.cshtml: v ...

Is there a way to remove the "next" button from the last page in a table?

I'm currently working on implementing pagination for my table. So far, I have successfully added both the "next" and "previous" buttons, with the "previous" button only appearing after the first page - which is correct. However, I am facing an issue w ...

Sort by the date using a specific data attribute

My main objective is to showcase a multitude of posts on this website, sourced from a server that does not organize them by date. I, however, wish to arrange them based on their dates. Currently, the layout on my website looks something like this: < ...

When working with data in Angular, make sure to use any[] instead of any in app.component.html and app.component.ts to avoid causing overload errors

I'm new to working with Angular, specifically using Angular 15. I have a Rest API response that I need to parse and display in the UI using Angular. To achieve this, I employed the use of HttpClient for making GET requests and parsing the responses. ...

When placed within a setInterval loop, the event.clientY variable becomes inaccessible

I am working on a script to move an element around a web page, and I have encountered a problem. Whenever I try to put it in a loop using setInterval while the mouse is down and moving, I receive an error message stating 'Uncaught TypeError: Cannot re ...

Identifying audio elements with Modernizr technology

I have incorporated the HTML 5 audio element in my coding: var audioElement = document.createElement('audio'); This object is utilized to facilitate playing audio from a designated source. Is there a way to identify this code using modernizr? ...

What is the best way to use JavaScript to show a text value alongside radio buttons?

Currently, I am in the process of creating an e-commerce platform that allows customers to choose custom components for their purchases. Although I am relatively new to JavaScript, I have successfully developed a radio button list where the prices are tota ...

What is the best way to extract value from a specific link using JavaScript?

I have a PHP script that retrieves data from a database: <?php while($trackResultRow = mysqli_fetch_assoc($trackResult)){?> <a onclick="remove()"><span class="glyphicon glyphicon-thumbs-down pull-right"></span></a> < ...

Encountering Issue with Node.JS and Socket.IO Example: Debugging Error on MAC OSX Localhost. Static Content File '/socket.io.js' is not loading properly

Recently, I started working with node.js and decided to incorporate the socket.io module. However, I encountered some issues with it not functioning as anticipated. The example that I am trying to replicate can be found at: I realized that the version of ...

Exploring the process of adding tooltips to column headers in ngx-datatable

I am attempting to display simple tooltips on the header of my ngx-datatable-column. It is important that I can still use the sort functionality. For some reason, the "title" attribute is not working as expected. <ngx-datatable-column title="my Toolti ...

Remove all child subcategories within the selected (sub)category from a cascading dependent dropdown menu selection

I'm currently working on implementing chained dependent dropdown combobox selection. The idea is to have one combobox for the main category, and once the main category is selected, another <select> will appear for choosing a subcategory, and so ...

Please rewrite the following sentence: "I am going to the store to buy some groceries."

As I navigate through my styled HTML page, an interesting sequence of events unfolds. When the Create New List button is clicked, a pink div emerges, contrasting with the orange hue of the All Lists div. At this moment, a new user has joined but hasn' ...

JavaScript does not show an error message if a function is called but has not been defined

Currently, I am developing a nodejs/reactjs application that incorporates a cache system. During my development process, I encountered an interesting error where the data stored in the cache was not being displayed by the component. After thorough investig ...

AngularJS enables seamless two-way data binding with DropDownList in the Model-View-Controller (M

As a beginner in AngularJS, I am currently experimenting with implementing 2-way data binding for the Gender Dropdown menu similar to what I have done with textboxes. Below is a snippet of code for the dropdown control: <div class="form-group"> ...

Unable to generate a navigation panel using HTML/CSS and jQuery

I recently completed the basic courses in HTML/CSS, JavaScript, jQuery, and PHP on Codecademy. I'm currently working on creating a website using HTML/CSS and jQuery in Codecademy's codebits. However, I'm facing some issues with my navigation ...