Display a div when a button is clicked and hide it when clicking outside of the div

I attempted to create a function for displaying and hiding a div. To hide the div, users can use the close button or click outside the div. However, I encountered an issue where the close function to hide the div runs first if the user clicks an element outside the div before the div is shown:

Here is the HTML code:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new-shipping'">Open Div</button>
<div id="add-shipping-modal" style="display:none">
  <button id="close-add">Close Div</button>
  <p> Show Me </p>
</div>

When clicking the #new-shipping button, the hidden div does not appear. This could be due to the fact that when the #new-shipping button is clicked, it first shows the div and then triggers the body click function.

Answer №1

Here is a solution already available on W3Schools.

To view the solution, click on this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal

Snippet

// Accessing the modal element
var modal = document.getElementById('myModal');

// Getting the button that triggers the modal
var btn = document.getElementById("myBtn");

// Accessing the close button within the modal
var span = document.getElementsByClassName("close")[0];

// Opening the modal when the button is clicked
btn.onclick = function() {
    modal.style.display = "block";
}

// Closing the modal when the close button is clicked
span.onclick = function() {
    modal.style.display = "none";
}

// Closing the modal when clicking outside of it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
/* Styling for the Modal background */
.modal {
    display: none; /* Initially hidden */
    position: fixed; /* Fixed positioning */
    z-index: 1; /* On top of everything */
    padding-top: 100px; /* Spacing from the top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Allowing scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color for older browsers */
    background-color: rgba(0,0,0,0.4); /* Black with opacity */
}

/* Styles for the Modal content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* Close Button styling */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
<h2>Modal Example</h2>

<!-- Button to trigger the Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal itself -->
<div id="myModal" class="modal">

  <!-- Content inside the Modal -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some sample text in the Modal..</p>
  </div>

</div>

Answer №2

You put an extra apostrophe in your code after new-shipping

<button id="new-shipping'">Open Div</button>

It should be

 <button id="new-shipping">Open Div</button>

https://jsfiddle.net/bntnfhLm/

Additionally, please modify the body click function by using preventdefault/stopPropagation

$("#add-shipping-modal").click(function(e){
    e.stopPropagation();
});

$(document).click(function(){
    $("#add-shipping-modal").hide();
});

Answer №3

Give this a shot

 $('#new-shipping').on('click', function () {
            $("#add-shipping-modal").show();
            return false;
        });

        $(document).click(function (event) {
            $("#add-shipping-modal").hide();
        });

Answer №4

give this a shot

$('#close-add').on('click', function () {
            $("#add-shipping-modal").hide();
        });

        $('#new-shipping').on('click', function () {
            $("#add-shipping-modal").show();
            return false;
        });
        $("#add-shipping-modal").click(function () { return false; });

        $(document).click(function (event) {
            $("#add-shipping-modal").hide();
        });

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

Sharing data between functions in jQuery AJAX promises

Struggling to define a variable in one promise method and use it in another? Here's the scenario: Take a look at this code snippet: $.getJSON('some/file/') .done(function(response) { var bar = response; }) .always(function() { // N ...

The webpage freezes when attempting to run jQuery with Selenium

I'm currently facing an issue where my selenium script hangs the webpage whenever I try to find an element using jQuery. The script doesn't execute and a pop up appears in the browser with the message "A script on this page may be busy, or it may ...

changing the visible style of a div element using JavaScript

I'm having an issue with a link on my webpage that is supposed to show or hide a <div id="po" style="display:none;">some html</div> element. The first time I click the link, the div displays properly. However, after tha ...

Encountering an error with the ".ts" file extension when attempting to execute a ts-node script

I am currently facing an issue while trying to execute a script that consists of two .ts files in a regular folder. One file contains the script, and the other has helper functions required to run it. Additionally, I am importing external libraries such as ...

What method can be used to effectively track markups within a string?

If this question has been posed differently before, please direct me to it as I couldn't locate it in my search results. I am interested in parsing text for various mark-ups, similar to those found on SO. eg. * some string for bullet list eg. *som ...

What is the best method for combining several variables into a single one using a parameter?

On the webpage, there is a table containing 11 checkboxes. I am looking to create a keyword that allows testers to input just 1, 2, or 3 to select a specific checkbox without needing multiple lines of element variables. Here are the elements: xpath=(//in ...

Ways to send user input to a function within a React component

I am currently working on implementing a simple feature where users can search posts by their tags. To achieve this, I have created the Feed.jsx component with the following code: "use client"; import { useState, useEffect } from "react&quo ...

Refresh the Page or URL After Submitting a Form using JavaScript or PHP

Just a heads up: I'm fairly new to the world of web development. Currently, I'm in the process of crafting an event calendar using CodeIgniter. However, I've hit a bit of a snag. Whenever I try to update an event using JavaScript, the page ...

What is the best way to ensure that the background of wrapped text extends precisely to the pixel distance of the text?

Having a simple issue that I believed could easily be solved with modern CSS, but I'm now confused. I was aiming to have the background of a text parent span precisely across the width of its longest text line, evenly spreading on the sides, different ...

Organizing a series of objects into groups of four for processing

I have a task of organizing an array of objects that represent game players by assigning each player to a group number based on their current group value. The challenge is to ensure that each group has as close to four players as possible, while also acco ...

Issue with Date Picker not properly storing selected date in MySQL database

My goal is to save the datepicker date to MySQL by selecting the date format using JavaScript. I have verified that the date format appears correct as YYYY-MM-DD when logging to the console. However, when I try to execute an INSERT query to MySQL, the date ...

Issues with Contenteditable functionality in JavaScript

My goal is to make a row editable when a button is clicked. $(":button").click(function(){ var tdvar=$(this).parent('tr').find('td'); $.each(tdvar,function(){ $(this).prop('contenteditable',true); }); }); <s ...

JQuery is having trouble with playing multiple sound files or causing delays with events

I've been working on a project that involves playing sounds for each letter in a list of text. However, I'm encountering an issue where only the last sound file is played instead of looping through every element. I've attempted to delay the ...

Despite successfully passing props into V-for, the output does not display the props as expected

I've been attempting to accomplish a straightforward task, but for some reason, it's not working and I can't figure out why. Within the parent component, App.vue, I have the following: data() { return { servers: [ { ...

Utilizing PHP to create an interactive website

As a novice PHP developer, I took to Google in search of tutorials on creating dynamic PHP websites. What I found was that many tutorials used the $_GET variable to manipulate URLs and make them appear like this: example.com/?page=home example.com/?page= ...

Working with Facebook Graph API data using javascript

I am attempting to parse output results from the Facebook Graph API (specifically comments on a website). Below is the script I am using: if (document.getElementById('comments')) { var url = "https://graph.facebook.com/fql?q=select+xid%2C ...

What is the process for incorporating Angular.js with a live messaging platform such as Pusher or PubNub?

Can Pusher or PubNub be implemented as an Angular service? Anyone have any examples of code for this kind of integration? ...

Oops! Looks like there was a NotFoundError when trying to execute the 'removeChild' function on React with Flickity

I am currently developing a React application, and I have integrated the 'CategoriesList' component on the HomePage. Everything works fine when I am on the HomePage, but I encountered an error when I navigated to the ProductDetails page using re ...

Vercel's Open Graph Image Generation encountering Failure - ERR_MODULE_NOT_FOUND

I am currently working on a project that utilizes NextJS and is deployed on Vercel. In an attempt to generate images, I am using the @vercel/og Open Graph Image generation library. However, each time the api route for the OG image is called, it leads to an ...

Upgrading object based on dynamic data shifts in Vue using Vuex

My current task involves updating data in a component based on the selection made from a tabs list at the top of the page. The data is sourced from a Vuex data store, and after conducting tests on the data store, everything appears to be functioning correc ...