Reputation: 1374
I am trying to make a append menu on click div. But i have one question here. How can i remove appended elements after second click. Anyone can help me in this regard ?
This is the DEMO page from codepen.io
Js
$(document).ready(function(){
$("body").on("click", ".menu-button", function(event){
event.preventDefault();
$(".menu-container").append('<div class="button"></div><div class="rebackbar"></div><div class="abc" id="myDiv"></div><div class="lBrgF"><div class="card"><span class="three-quarters-loader">Loading… </span></div></div>');
});
});
Upvotes: 2
Views: 2439
Reputation: 951
Append the content only if the content not exist.
$(document).ready(function() {
$("body").on("click", ".menu-button", function(event) {
event.preventDefault();
if (!$('.button').length) {
$(".menu-container").append('<div class="button"></div><div class="rebackbar"></div><div class="abc" id="myDiv"></div><div class="lBrgF"><div class="card"><span class="three-quarters-loader">Loading… </span></div></div>');
} else {
$(".menu-container").html(''); // Empty after
}
});
});
Upvotes: 1
Reputation: 76
By no means the most elegant solution but probably the easiest:
$(document).ready(function(){
$("body").on("click", ".menu-button", function(event){
event.preventDefault();
if($('.menu-container').html().length > 0) {
$(".menu-container").html(null)
}
else {
$(".menu-container").html('<div class="button"></div><div class="rebackbar"></div><div class="abc" id="myDiv"></div><div class="lBrgF"><div class="card"><span class="three-quarters-loader">Loading… </span></div></div>');
}
});
});
Upvotes: 1
Reputation: 2156
Here's another solution
I've called the dblclick
event to empty the contents of the menu-container
.This empties the entire div.Incase you want to remove the last child, you can find the length and remove the last one that way.
$("body").on("dblclick", ".menu-button", function(event){
$(".menu-container").empty();
});
Upvotes: 1
Reputation: 207511
Seems like toggling the element instead of adding it would be better, but you could just put a check
var childNodes = $(".menu-container").children();
if (childNodes.length) {
childNodes.remove();
} else {
$(".menu-container").append("...");
}
Upvotes: 3