Is there a way to disable the popup background when we click anywhere on the page?

There is a button that, when clicked, opens a popup with a disabled background. However, if I click anywhere on the page outside of the popup, it does not enable.

<a href="#" onClick="openPopup('popUpDiv')">Click here to open the popup</a>

<a href="#" onClick="closePopup('popUpDiv')">Close</a>

<script type="text/javascript">
function openPopup(div) {
    document.getElementById(div).style.display = 'block';
}
function closePopup(div) {
    document.getElementById(div).style.display = 'none';
}
//Detecting the escape key
document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        closePopup('popUpDiv');
    }
};
</script>

Answer №2

Bootstrap simplifies the process of creating popups.

<!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Modal Popup Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
      <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>

    <div class="container">
      <h2>Modal Popup Example</h2>
      <!-- Trigger the modal with a button -->
      <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

      <!-- Modal -->
      <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">

          <!-- Modal content-->
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
              <p>Some text in the modal.</p>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
          </div>

        </div>
      </div>

    </div>

    </body>
    </html>

If you prefer using only javascript,

<!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

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

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

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
</style>
</head>
<body>

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

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

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    <p>Some text in the Modal..</p>
  </div>

</div>

<script>
// Get the modal
var modal = document.getElementById('myModal');

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

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

</body>
</html>

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

How to Activate ng-animate in AngularJS When Data Binding Value Changes

Within my directive, I am binding some content using ng-html-bind-unsafe. I would like to incorporate a transition effect when the content changes. One option is to apply a fade-out effect using jQuery, update the content, and then fade it back in. Is the ...

Is it possible to retrieve an element styled inline, such as an input?

Is it possible to style elements with inline styling using a selector such as div[style=float:right;] {}? For example: <div style="float: right;"></div> ...

BxSlider border frame glitch – troubleshooting tips

This is my first attempt at creating a website, so please excuse my simple question. I am currently using bxslider for the banner on my website. However, I have noticed that there is excessive border on the left side. How can I adjust it to be even with th ...

How come my JavaScript array isn't successfully passing data through AJAX?

let itemList = new Array(); function saveItem(id){ let title = $("#inputTitle_"+id).val(); let url = $("#inputPicurl_"+id).val(); let content = $("#content-editor-"+id).html(); itemList[id] = new Array(); itemList[id]['inputTit ...

How come the action doesn't trigger in my React/Redux application?

Currently, I am in the process of developing a small application that incorporates modals. Instead of relying on pre-made packages like react-modal, I have taken the initiative to build the modal functionality from scratch. 1) Defining a reducer located i ...

The average duration for each API request is consistently recorded at 21 seconds

It's taking 21 seconds per request for snippet.json and images, causing my widget to load in 42 seconds consistently. That just doesn't seem right. Check out this code snippet below: <script type="text/javascript"> function fetchJSONFil ...

Setting a header with the Axios module and Vue.js in Nuxt: A step-by-step guide

I've been attempting to set up an "Accept-Language" header for my SPA using vue.js (along with nuxt). Here's the approach I took, but unfortunately, it's not functioning properly. I specified that I am utilizing the axios module for nuxt. ...

What is the method for applying a class to another element?

Thanks to the amazing help from ori, I've successfully implemented a script that works exactly as I wanted. However, my limited knowledge of jQuery is hindering me from getting the next phase up and running! My goal now is to enhance it further by as ...

Comprehending the intricacies of routing within AngularJS

Question: I've been looking into this issue, but there seems to be conflicting answers. I created a simple example in Plunker to understand how routers work in AngularJS, but I'm having trouble getting it to function properly... Below is my inde ...

Troubleshooting: jQuery's AJAX load() function fails to execute

I am facing an issue where I am attempting to import an HTML file into a specific section within my webpage using the load() method. However, when I click on the link, instead of loading the HTML file into the designated div tag, it opens in a new tab. He ...

What is preventing me from sending back an array of objects with an async function?

Working with node.js, my goal is to retrieve a list of bid and ask prices from a trading exchange website within an async function. While I can successfully log the object data using console.info() within the foreach statement on each iteration, when attem ...

MVC Template with a Defective BootStrap

Struggling with creating an MVC master template along with sub-pages using Bootstrap. Sadly, I seem to have messed it up and can't quite figure out where the problem lies. You can check out my test website at Do you see how the different sections a ...

employing the $.getJSON method for fetching CSV information

I've been experimenting with Yahoo's Finance API to fetch stock data: $.ajax({ dataType: "json", url: 'http://download.finance.yahoo.com/d/quotes.csv', data: 's=RHT+MSFT&f=sb2b3jk&am ...

What is the method to advance the opposing line in the dynamic chart?

Here is the link to the code for a dynamic graph. I am struggling with keeping the red line updated and moving forward together with the blue line. I cannot figure out why the red line remains static in the dynamic graph. Any suggestions on how to solve t ...

The float:left property within a div is not behaving as anticipated

I am having trouble positioning my second div. In order to have 70% of my website for posts and 30% for a small text display, I created a new div. I believe the correct way to position it is by using "float: left" so that the div goes under the banner whe ...

Using jQuery AJAX to pass two arrays, splitting them, and utilizing them independently in Laravel

Whenever I update the selection in a dropdown list within a view, I use an ajax call in a controller to retrieve 2 arrays and update 2 other dropdown lists in the same view with the returned data in Laravel. The controller method looks like this: public ...

What are some ways to avoid the use of underline and slash symbols in material-ui/pickers?

Is there a way to remove the underline and slash characters that separate day, month, and year in the material ui pickers for version mui version 4? <KeyboardDatePicker margin="normal" id="date-picker-dialog" label="Dat ...

Discover the "route" of a JSON element using JavaScript

I've been struggling to retrieve the "path" of a specific AngularJS scope variable. My end goal is to utilize this "path" as the ng-model for dynamically generated forms. Below is my current code: my_code.js: var my_data = { name: "fred", numbe ...

Tips for activating a text box by pressing a key without actually typing the key into the box

Is there a way to focus on a text box whenever the user presses the 'S' key on the keyboard, without actually typing the 'S' character in the text box itself (this issue only occurs in Chrome)? Here is the code I have so far: $(documen ...

Parsing URLs with Node.js

Currently, I am attempting to parse the URL within a Node.js environment. However, I am encountering issues with receiving null values from the following code. While the path value is being received successfully, the host and protocol values are returnin ...