Hide the popup menu when the user clicks outside of it

I am presenting the following code

<!DOCTYPE html>
<html>
<head>
    <title>GalacticCraft</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <link rel="shortcut icon" type="image/png" href="favicon.ico">
</head>
<body>
<div id="staff"></div>
    <div id="portal">
        <img id="logo" src="assets/logo.png">
        <div id="buttons">
            <a href="http://forums.galacticmc.net"><div class="button" id="button1"></div></a><a href="http://store.galacticmc.net"><div class="button" id="button2"></div></a><a href="http://galacticmc.net/rules"><div class="button" id="button3"></div></a><div class="button" id="button4" onclick="staff()"></div><a href="http://galacticmc.net/vote"><div class="button" id="button5"></div></a>
        </div>
    </div>
</body>
</html>
<script>
function staff() {
    document.getElementById('staff').innerHTML = `
<div class="popup" onclick="close()"></div><img src="assets/close.png" class="close-icon" onclick="close()"><div class="popup-menu"><a href="http://www.galacticmc.net/staff-application"><img src="assets/apply.png" class="apply"><p>Apply to become a member of staff</p></a><hr><a href="http://galacticmc.net/staff"><img src="assets/staff.png" class="list-staff"><p>View Staff Members</p></a></div>
    `
}

</script>

and CSS

.popup {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    position: absolute;
    z-index: 5;
    opacity: 0.5
}
.popup-menu {
    top: 0;
    width: 700px;
    height: 99.6%;
    background-color: #fff;
    position: absolute;
    z-index: 10;
    left:calc(50% - 351px);
    border: 2px solid #808080;
        -webkit-animation: fadein 1s; /* Safari, Chrome and Opera > 12.1 */
       -moz-animation: fadein 1s; /* Firefox < 16 */
        -ms-animation: fadein 1s; /* Internet Explorer */
         -o-animation: fadein 1s; /* Opera < 12.1 */
            animation: fadein 1s;
    padding-left: 20px;
}
.apply {
    width: 350px;
    height: 350px;
    position: relative;
    left: calc(50% - 185px);
}
.popup-menu p {
    color: #009AFF;
    text-align: center;
    font-size: 35px;
}
.popup-menu a {
    text-decoration: none 
}
.list-staff {
    width: 350px;
    height: 350px;  
    position: relative;
    left: calc(50% - 185px);
}
.close {
    position: absolute;
    top: 2px;
    right: 2px;
}
html {
    background-image: url("assets/bg.png");
    background-size: 100%;
    overflow: hidden;
    width: 100%;
    height: 100%;
}
#portal {
    bottom: 0;
    height: 550px;
    left: 0;
    margin: auto;
    position: absolute;
    right: 0;
    text-align: center;
    top: 0;
    width: 1000px;
}
#buttons {
  bottom:75px;
  height:200px;
  position:absolute;
  width:1000px;
}

.button {
  background-position:center;
  background-repeat:no-repeat;
  background-size:190px;
  cursor:pointer;
  display:inline-block;
  height:200px;
  transition:background-size .2s ease;
  width:200px;
}

.button:hover {background-size:200px}
.button:active {background-size:180px}

#button1 {background-image:url("assets/forums.png")}

#button2 {background-image:url("assets/store.png")}

#butt

on3 {background-image:url("assets/rules.png")}

#button4 {background-image:url("assets/staff.png")}

#button5 {background-image:url("assets/vote.png")}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

Study our JSFiddle for further details https://jsfiddle.net/vgjvzmp5/

Upon clicking "Click me", you will observe a popup window appearing. It is functioning as intended, but how can I implement a method to close it when the faded background or the close icon in the corner is clicked? This implementation should be done using pure Javascript.

Answer №1

Check out this easy solution below. No need to constantly insert new html elements upon click. Simply include them in your html file with display:none and utilize javascript for toggling visibility:

function display() {
    document.getElementById('modal').style.display = 'block';
}

function vanish() {
    document.getElementById('modal').style.display = 'none';
}

https://jsfiddle.net/abcd1234/7/

Answer №2

To prevent event propagation, make sure to utilize the stopPropagation() method.

Check out a preview on CodePen!

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

ways to instantly showcase the input's value within a DIV element

For example, I have a div with the ID of "someDiv" and an input text field with the ID of "someInput". How can I make it so that the value entered into the input field displays in the DIV in real time? For instance, if I type the letter "a" in the input fi ...

Uncovering the secrets: accessing hidden folder files in react-native-fs

I am encountering a problem when trying to access files from a hidden folder /WhatsApp/Media/.Statuses in react-native-fs. Despite granting the READ_EXTERNAL_STORAGE permission on Android, I only receive an empty array when attempting to access it using th ...

Maintain dropdown menu visibility while navigating

I'm having an issue with my dropdown menu. It keeps sliding up when I try to navigate under the sub menu. I've spent all day trying to fix it, testing out various examples from the internet but so far, no luck. Any help would be greatly apprecia ...

How come the mongoose ref feature is not functioning properly for me when I attempt to reference objects from a different schema?

I'm having trouble accessing the attributes of a store's address, as I keep getting 'undefined'. It seems that the address is only an id, even though I set up a 'ref' in the address schema. What could be causing this issue? H ...

Mysterious data organization - transform into an object

As I interact with an API, there is a value that I cannot quite pinpoint. My goal is to transform this string into a JavaScript object, but the process seems complex and confusing. Does anyone have insight on what this data represents and how it can be co ...

A step-by-step guide on utilizing jQuery to cyclically change the background color of elements upon clicking, and resetting the colors upon clicking another element

So I've been working on a solution to change the background color for accessibility purposes on a client's website. To achieve this, I have a set of div elements with different background colors and I'm using jQuery to update the body backgr ...

jQuery for validating input fields with positive integers only using regular expressions

I currently have two input fields in my HTML that look like this: <input type="text" class="txtminFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Minimum Feedback"> <input type="text" class="txtmaxFeedback" pattern="^\d ...

Implement real-time reporting functionality in Selenium

I have been working on implementing a run-time reporting mechanism for my automated test cases created using Java with Selenium and TestNG. The test results and details are stored in a MySQL database. Although I can successfully insert the test results in ...

Having difficulties with hovering over a td that has a rowspan

I am encountering some challenges when attempting to hover over a td with rowspan in my HTML table. Despite searching for a solution, I have not been successful. I came across suggestions on forums that hinted at using JS/jQuery. Could someone please provi ...

Splitting code efficiently using TypeScript and Webpack

Exploring the potential of webpack's code splitting feature to create separate bundles for my TypeScript app has been a priority. After scouring the web for solutions, I stumbled upon a possible lead here: https://github.com/TypeStrong/ts-loader/blob/ ...

Error: Primefaces ajax status failure (dialog has not been defined)

I incorporated the same code found on primefaces.org, specifically this link: http://www.primefaces.org/showcase/ui/ajaxStatusScript.jsf <p:ajaxStatus onstart="statusDialog.show();" onsuccess="statusDialog.hide();"/> <p:dialog modal="true" ...

Dynamic JavaScript button control based on time

I am currently working on an app and my goal is to have a feature where the user clicks a button, it will then disappear and only reappear after 24 hours. Here's my progress so far. <div class="buttons"> <p><button onclick="hide(); ...

Is there a way to retrieve the value of an HTML variable using Selenium?

Seeking assistance in determining the progress value of a video using Selenium. I understand that I need to utilize JavaScript executor, but have been unsuccessful in finding a solution so far. The element in question is: <div aria-label="scrub bar" a ...

Cool ways to showcase HTML content in AngularJS

I am completely new to AngularJS. My goal is to display HTML content on the view using AngularJS. I initially tried using ng-model, but it displayed HTML content as a string on the view. After that, I attempted to use ng-bind-html which worked for the in ...

Phrases are truncated in the initial line of each ion-item within the ion-list

In Ionic 3, I am facing an issue with my ion-list where the first line inside each ion-item is getting cut off. Specifically, the capital 'A' letter is not entirely visible. Can anyone provide assistance with this? Thank you. Below is my code sn ...

Choose from a dropdown menu to either activate or deactivate a user account

I'm new to php and I need help getting this code to function properly delete.php <?php include_once 'dbconfig.php'; if($_POST['del_id']) { $id = $_POST['del_id']; $stmt=$db_con->prepare("UPDATE tbluse ...

Is there a way to display multiple images in a JSON message object?

If you're looking for a fun way to generate random dog images, then check out my DogAPI image generator! Simply enter a number between 1-50 into the form text box, hit send, and watch as it displays that amount of random dog photos. I'm almost t ...

Can JSON encoding in a URL pose a risk of XSS attacks?

To ensure my application has URL-friendly capabilities, I am storing its context as a JSON within the URL. This results in something like: http://mysite.dev/myapppage/target#?context={%22attr1%22%3A{%22target_id-0%22%3A{%22value%22%3A%223%22%2C%22label%2 ...

Creating a grid cell that spans the entire grid width

Snippet of CSS Code: .wrapper { display: grid; position: relative; grid-template-columns: repeat(4, 1fr); grid-auto-rows: 25vh; width: 100%; } .prova { border: 1px solid; } .wrapper div:nth-child(2) { grid-column: 3; grid-row: 2 / 4; ...

Managing JavaScript promise rejections

What is the best approach to managing an error, such as the one labeled "new error" in the code snippet below, that occurs outside of a promise? function testError() { throw new Error("new error") // How can this error be properly handled? var p ...