Clicking outside the div will cause the div to be hidden

Looking for some help with a jQuery issue. I have a pop-up that opens when a div is clicked, but I want it to close when clicking outside of the div instead of just on the close button.

<a class="close-up" href="#" onclick="popup('popUpDiv')" >X</a>

The div structure is as follows:

<div id="blanket" style="display:none;"><a class="close-up" href="#" onclick="popup('popUpDiv')" >X</a></div>
<div id="popUpDiv" style="display:none;">  <div class="main-navBar">kfbkasfkafkja</div> </div>  

If anyone can assist with making the pop-up hide when clicking outside the div, it would be greatly appreciated. Thanks in advance...

Answer №1

Check out this solution:

$(document).mouseup(function (event)
{
    var box = $("#popupContainer");

    if (!box.is(event.target) && box.has(event.target).length === 0) 
    {
        box.hide();
    }
});

Answer №2

I have created an example using jQuery that utilizes a different approach. Instead of monitoring everything outside of a div, it adds a covering and waits for the user to interact with it by clicking. This concept is reminiscent of Bootstrap's modals.

$('#open-popup').click(function() {
  $('#popup').show();
});

$('.popup_wrap .blanket').click(function() {
  $(this).parent().fadeOut(100);
});
html,
body {
  border: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}
.popup_wrap{
  display: none;
}
.popup_wrap,
.blanket {
  height: 100%;
  width: 100%;
  position: absolute;
}
.blanket {
  z-index: 1000;
  display: inline-block;
  background-color: rgba(0, 0, 0, 0.5);
}
.popup {
  z-index: 1001;
  display: inline-block;
  position: absolute;
  background-color: #fff;
  width: 50%;
  margin: 50px 25% 0 25%;
  padding: 5px;
}
.fake-link{
  text-decoration: underline;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='popup' class='popup_wrap'>
  <div class='popup'>
    Some text...
  </div>
  <div class='blanket'></div>
</div>

<span id='open-popup' class='fake-link'>Open Popup</span>

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

Unspecified variable in AngularJS data binding with Onsen UI

I am new to Onsen UI and AngularJS, and I have a simple question about data binding. When I use the variable $scope.name with ng-model in an Onsen UI template, it returns as UNDEFINED. Here is my code: <!doctype html> <html lang="en" ng-app="simp ...

Bringing in More Blog Posts with VueJS

Exploring the Wordpress API and devising a fresh blog system. As a newbie to VueJS, I'm intrigued by how this is handled. The initial blog posts load as follows: let blogApiURL = 'https://element5.wpengine.com/wp-json/wp/v2/posts?_embed&p ...

The ASP.NET MVC3 form collection registers as 0 when performing a jQuery ajax post

I'm currently developing a project on ASP.NET MVC3. My current challenge involves POSTing to a method that should return a set of data using the jQuery.ajax api. However, upon handling the request on the server, I noticed that the form collection&apo ...

Guide on adding pictures to an ExpressJS server

Working on this project has been quite a challenge for me as I delve deeper into web development. As a relatively new developer, creating a one-page application with image upload functionality has proven to be quite the task, especially considering this is ...

One click activates the countdown timer, while a second click on the same button pauses it

How can I create a button that allows me to start the countdown timer on the first click and pause it on the second click? I want both functionalities in the same button. Here is an image for reference: https://i.stack.imgur.com/fuyEJ.png I currently ha ...

I am looking for a way to display or conceal text depending on the presence of an image

Could you please help me with this? I am looking for a solution where text is displayed only when there is content in the src attribute of an img tag. Essentially, I need JavaScript code that can identify if an attribute has content and then make a paragra ...

The situation where a Javascript switch case continues to fall through to the default case even when a 'break' statement

I am currently setting up a node.js discord bot that utilizes firebase to save a user's status. My switch statement is functioning smoothly, handling each command effectively. The default case looks like this: default: message.reply("Unknown comm ...

Regular expression patterns for authenticating and verifying passwords

Currently, I am working on a JavaScript program to validate passwords using regex. Here are the requirements: The password must consist of at least seven characters. It should include at least one of the following: an uppercase letter (A-Z) a lowercas ...

Tips for moving a title sideways and adjusting the bottom section by x pixels

I am seeking to accomplish a design similar to this using CSS in order to create a title of <h1>DISCOVER <span>WEB 3</span> DIMENSIONS</h1>. How do you recommend achieving this? Thank you, I have searched on Google and asked frie ...

Seeking assistance with downloading a collection of images as a zipped file using AngularJS

My code was previously working with jszip 2x but now I'm getting an error stating "This method has been removed in JSZip 3.0, please check the upgrade guide.". Even after following the upgrade guide, my code is still not functioning properly. I need a ...

When text with delimiters is pasted into a Vuetify combobox, why aren't the chips separated correctly by the delimiters?

I'm attempting to create a Vuetify combobox with chips that automatically split the input based on predefined delimiters, such as ,. This means that if I paste the text a,b,c, the component should convert them into three separate chips: a, b, and c. H ...

Using AngularJS, you can easily preselect an option in a select menu that is populated using ng-options

Exploring how to use AngularJS ng-option directive to populate a select menu and set a default option. The JSON data retrieved by AngularJS: {"AF":"Afghanistan","AX":"\u00c5land Islands","AL":"Albania","DZ":"Algeria","AS":"American Samoa","AD"} The ...

React-app size has grown larger post-deployment

I recently created my second app clone using React. I have noticed that after deployment, the size of the app increases. Everything looks normal on localhost:3000, but it significantly grows once deployed. Any assistance in resolving this issue would be gr ...

Is there a way to use a media query on a div element to check for the presence of a scroll bar?

A div has been styled with overflow-y: auto, triggering the appearance of a vertical scroll bar when the content exceeds the height of the div. This causes the content to shift horizontally to accommodate the scroll bar, resulting in misalignment with the ...

Tips for incorporating a spinner during content loading within AngularJS

When the user clicks on the "Search" button, content will load and the button label will change to "Searching" with a spinner shown while the content is loading. Once the content has loaded (Promise resolved), the button label will revert back to "Search" ...

React does not allow objects as child elements. Instead, render a collection of children by using an array

Encountering an error with this React class Error: Objects are not valid as a React child (found: object with keys {_id, name}). If you meant to render a collection of children, use an array instead. Is there anything amiss here? I am passing the movies ...

NextJS getStaticProps failing to pass fetched data to the page component

Struggling with passing props from getStaticProps function into template pages in NextJS. Below is the code for the dynamic page template that I am using. // src/pages/blog/[slug].js import React from 'react'; import matter from 'gray-matte ...

Node.js tutorial: Building routes with regex and implementing redirects

Can anyone provide guidance on how to utilize route and redirect URLs with parameters in Node.js using Express? If the URL is xyz/?s=test, it should redirect to indexRouter. If the URL is xyz/, it should also redirect to indexRouter. I'm facing issu ...

Obtain abbreviated names for the days of the week starting from Monday to Sunday using JavaScript

Is there a way to retrieve the abbreviated names of each day of the week in JavaScript, starting from Monday through Sunday? ...

Creating a personalized .hasError condition in Angular 4

I am currently in the process of modifying an html form that previously had mandatory fields to now have optional fields. Previously, the validation for these fields used .hasError('required') which would disable the submit button by triggering a ...