I am trying to figure out how can I remove a pop-up div element using the .remove()
jQuery method. I have a div which is appended to the #main div when the I click 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?
This is to remove the popup by clicking on the background
$('.popUpBg').on('click', function() {
$('.popUpItSelf').remove();
});
To remove both the background and the pop up, just do this.
$('.popUpBg').on('click', function() {
$('.popUpItSelf, .popUpBg').remove();
});
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>");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.