tonix tonix - 3 months ago 7
CSS Question

How to remove a pop-up div appended with .append() method using JQuery?

I am trying to figure out how can I remove a pop-up div element using the .remove() JQuery's method. I have a div which is appended to the #main div when the I clicks on an element with class ".popUpTrigger". Then I would like to remove this appended html code when I click on the pop-up itself.

Here is my HTML:

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html"/>
<meta charset="utf-8"/>
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="jscript.js"></script>
<link rel="stylesheet" href="style.css" type="text/css">
<title>Title</title>
</head>
<body>
<div id="main">
<button class="popUpTrigger">Click to trigger the popUp!</button>
</div>
</body>
</html>


My jscript.js:

function popUpCreate(idToAppend, popUpCode) {
$(function() {
$(idToAppend).append(popUpCode);
});
}


$(function() {
$(".popUpTrigger").click(function() {
popUpCreate("#main", "<div class='popUpBg'><div class='popUpItSelf'>Hello!</div></div>");
});
});

$(function() {
$(".popUpBg").click(function() {
$(".popUpBg").remove();
});
});


The style.css file:

.popUpBg {
position:fixed;
z-index:999999;
top:0;
width:100%;
height:100%;
background:rgba(0,0,0,0.8);
cursor:pointer;
}

.popUpItSelf {
position:fixed;
z-index:9999999;
width:400px;
height:200px;
text-align:center;
top:50%;
left:50%;
margin-left:-401px;
margin-top:-301px;
background:white;
border: 1px solid black;
font-size: 4em;
color:black;
font-weight:bold;
padding:200px;
}


But it does not work, I want the pop-up to be removed when I click on the .popUpBg (which is the pop-up background). How can I achieve that?

Answer

You append an handler on click for an object (the background) that not yet exists.

First, I rewrite your own code to be more readable

function popUpCreate(idToAppend, popUpCode) {
   $(idToAppend).append(popUp);
}

$(".popUpTrigger").click(function() {
    popUpCreate("#main", "<div class='popUpBg'><div class='popUpItSelf'>Hello!</div></div>");
});


$(".popUpBg").click(function() {
    $(".popUpBg").remove();
});

Now, I make the correction

function popUpCreate(idToAppend, popUpCode) {
    $(idToAppend).append(popUp);
    $(".popUpBg").click(function() {
        $(".popUpBg").remove();
    });
}

$(".popUpTrigger").click(function() {
    popUpCreate("#main", "<div class='popUpBg'><div class='popUpItSelf'>Hello!</div></div>");
});