I create a clone function with jquery and included a deleted button inside it, when i click the delete button it will delete the particular box parent and hide the delete button when the delete button length < 2, i generate unique id for each box start from 1, it work when i delete the box with id in sequence start from 3,2,1 and 4 (from bottom to top box), but the delete button can't hide when i start delete start from 4,1,2,3 (from the top to the bottom), here my code below
$(document).ready(function(){
var counter = 1;
var total = 1;
var el = $('#clone');
var box = $('.box');
var container = '.container';
var deleteBtn = $('#delete');
$(document.body).on('click','#clone', function(){
counter ++;
total ++;
var startClone = box.clone(true);
startClone.appendTo(container);
box.attr('id','hallo' + counter);
$('.box').find('#delete').show();
deleteBtn.show();
})
$('#delete').on('click', function(){
total --;
$(this).closest('.box').remove();
console.log(total);
if(total < 2){
deleteBtn.hide();
}else {
deleteBtn.show();
}
})
})
.box {
background: red;
width: 100px;
height: 100px;
margin: 5px 0;
}
#clone {
display: block;
}
#delete {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div class="container">
<div class="box" id="hallo1">
<button id="delete">Delete</button>
</div>
</div>
<button id='clone'>Clone this</button>
</body>
</html>
id should be unique. When you clode box element there would be multiple buttons with id delete and will create issues.
I used class .delete. Please check.
$(document).ready(function() {
var counter = 1;
var el = $('#clone');
var box = $('#hallo1');
var container = '.container';
box.hide(); //Hide the orginal box
var clone = function(){
counter++;
var startClone = box.clone(true);
startClone.append(counter - 1); //For test purposes. Please remove
startClone.appendTo(container);
startClone.attr('id', 'hallo' + counter);
startClone.show(); //Show the cloned box
startClone.find('.delete').show();
toggleDelete();
}
var toggleDelete = function(){
if ($(".delete").length < 2) {
$(".delete").hide();
} else {
$(".delete").show();
}
}
clone();//Clone initaly
$(document.body).on('click', '#clone', function() {
clone();
})
$('.delete').on('click', function() {
$(this).closest('.box').remove();
toggleDelete();
})
})
.box {
background: red;
width: 100px;
height: 100px;
margin: 5px 0;
}
#clone {
display: block;
}
.delete {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box" id="hallo1">
<button class="delete">Delete</button>
</div>
</div>
<button id='clone'>Clone this</button>
Alternative cleaner Approach:
$(document).ready(function() {
$("#clone").click(function() {
clone();
toggleDelete();
});
$("body").on('click', '.delete', function() {
$(this).closest('.box').remove();
toggleDelete();
})
var toggleDelete = function() {
if ($(".delete").length < 2) {
$(".delete").hide();
} else {
$(".delete").show();
}
}
var clone = function() {
$("#container").append('<div class="container"><div class="box"><button class="delete">Delete</button></div></div>');
}
clone(); //Call init
});
.box {
background: red;
width: 100px;
height: 100px;
margin: 5px 0;
}
#clone {
display: block;
}
.delete {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>
<button id='clone'>Clone this</button>
Identifiers must be unique so assign a CSS then Class Selector can be used to target the element and You should use Event delegation to bind event with dynamic elements.
container.on('click', '.delete', function () {
$(this).closest('.box').remove();
if ($(".delete").length < 2) {
$(".delete").hide();
} else {
$(".delete").show();
}
});
$(document).ready(function() {
var el = $('#clone');
var box = $('.box');
var container = $('.container');
$(document.body).on('click', '#clone', function() {
var startClone = box.eq(0).clone();
startClone.appendTo(container);
$('.box').find('.delete').show();
})
container.on('click', '.delete', function() {
$(this).closest('.box').remove();
if ($(".delete").length < 2) {
$(".delete").hide();
} else {
$(".delete").show();
}
})
})
.box {
background: red;
width: 100px;
height: 100px;
margin: 5px 0;
}
#clone {
display: block;
}
.delete {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box" id="hallo1">
<button class="delete">Delete</button>
</div>
</div>
<button id='clone'>Clone this</button>
Related
The answer that I want:
This is a problem that causes the color to change when you press the box. A valid example will be provided by clicking on the hyperlink.
I don't know where this problem is wrong at the moment.
If you click on one of the three boxes, add an on class so that the box turns yellow.
Remove the on class so that the original yellow box becomes gray when you click the other box with only one box yellow.
const box = document.getElementsByClassName('.favorites_icon')
function onAndOff(event) {
for (let i = 0; i < box.length; i++) {
box[i].classList.remove('on');
event.target.classList.add('on');
}
}
for (let i = 0; i < box.length; i++) {
box[i].addEventListener('click', onAndOff)
}
.favorites_icon {
display: block;
width: 50px;
height: 50px;
background-color: #ccc;
margin-bottom: 10px;
}
.on {
background-color: yellow;
}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>box</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<i class="favorites_icon"></i>
<i class="favorites_icon"></i>
<i class="favorites_icon"></i>
<script src="jquery-3.5.1.js"></script>
<script src="index.js"></script>
</body>
</html>
jQuery solution
const boxes = document.querySelectorAll(".favorites_icon");
boxes.forEach(box => {
box.addEventListener('click', ()=> {
$(box).addClass('on');
$(box).siblings().removeClass('on');
});
});
.favorites_icon {
display: block;
width: 50px;
height: 50px;
background-color: #ccc;
margin-bottom: 10px;
}
.on {
background-color: yellow;
}
<i class="favorites_icon"></i>
<i class="favorites_icon"></i>
<i class="favorites_icon"></i>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
Plain javascript solution
const boxes = document.querySelectorAll(".favorites_icon");
boxes.forEach(box => {
box.addEventListener('click', ()=> {
let siblings = getSiblings(box);
// add yellow to clicked box
box.classList.add('on');
// remove yellow from siblings
siblings.forEach(el => {
el.classList.remove('on');
})
});
});
function getSiblings(e) {
let siblings = [];
if(!e.parentNode) {
return siblings;
}
let sibling = e.parentNode.firstChild;
while (sibling) {
if (sibling.nodeType === 1 && sibling !== e) {
siblings.push(sibling);
}
sibling = sibling.nextSibling;
}
return siblings;
};
.favorites_icon {
display: block;
width: 50px;
height: 50px;
background-color: #ccc;
margin-bottom: 10px;
}
.on {
background-color: yellow;
}
<i class="favorites_icon"></i>
<i class="favorites_icon"></i>
<i class="favorites_icon"></i>
--- UPDATED QUESTION ---
Thanks for all the answers. I wrote the JS code to delete the parent div when clicking its corresponding button in my JS PRACTICE!!!
However, the same JS code does not work in my real JS project where all the parent div are created dynamically. The complete code can be found below.
There is no error but the JS code just does not work. Any ideas?
BELOW IS THE SIMPLIFIED **REAL JS PROJECT ** COMPLETE CODE
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Imgs</title>
<style type="text/css">
.container {
width: 100%;
}
.display-area {
width: 100%;
height: auto;
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
}
img {
max-width: 100%;
}
.image-preview {
width: 80%;
min-height: 300px;
border: 2px dashed #dddddd;
display: block;
/*default text*/
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
color: #cccccc;
}
.newbtns {
border: 0;
background: lightgrey;
text-shadow: 1px 1px 1px white;
border: 1px solid #999;
position: absolute;
display: block;
}
</style>
</head>
<body>
<div class="container">
<div id='inputFiles'><input type="file" class="file" name="image_uploads" accept="image/png, image/jpeg, image/jpg"
multiple></div>
<div class="display-area" id='imgDisplay'>
</div>
<div id="defaultContent">
<p>No images</p>
</div>
<button type="button" value="Reload page" onclick="window.location.reload()">Reload Page</button>
</div>
</div>
</body>
<script>
var input = document.querySelector('input');
var uploadBox = document.getElementById('uploadBox');
var defaultContent = document.getElementById('defaultContent');
var imgDisplay = document.getElementById('imgDisplay')
//upload & preview
input.addEventListener('change', function () {
var imgFiles = input.files;
defaultContent.style.display = 'none';
for (var i = 0; i < imgFiles.length; i++) {
var imgDiv = document.createElement('div');
imgDiv.className = 'imgBox';
imgDiv.id = 'box' + i;
imgDiv.style.width = "20%";
var images = document.createElement('img');
images.src = URL.createObjectURL(imgFiles[i]);
var newbtn = document.createElement("button");
newbtn.type = "button";
newbtn.className = "newbtns";
newbtn.innerHTML = "X";
newbtn.style.color = "orange";
newbtn.style.background = 'red';
newbtn.id = 'newbtn' + i;
imgDiv.appendChild(newbtn);
imgDiv.appendChild(images);
imgDisplay.appendChild(imgDiv);
}
});
allButtons = document.getElementsByTagName('button');
for (var n = 0; n < allButtons.length; n++) {
if (allButtons[n].getAttribute('id') === 'newbtn' + n) {
allButtons[n].onclick = function () {
this.parentNode.parentNode.removeChild(this.parentNode);
}
} else { };
}
</script>
</html>
you can do something like this:
const buttonOne = document.getElementById('btn1');
const buttonTwo = document.getElementById('btn2');
buttonOne.addEventListener("click", () => deleteElementAndThisChildNodes('box1'))
buttonTwo.addEventListener("click", () => deleteElementAndThisChildNodes('box2'))
function deleteElementAndThisChildNodes(parentId) {
document.getElementById(parentId).remove()
}
To each of your button elements add onclick="DeleteParent(this)" then outside of your dynamic divs include the following:
<script type="text/javascript">
function DeleteParent(button){
button.parentElement.remove();
}
</script>
You can do this:
const display = document.getElementById("imgdisplayarea");
display.addEventListener("click", e => {
if(e.target.tagName === 'BUTTON'){
//if an element within a display div for a button, remove your father
e.target.parentNode.remove();
}
});
Here is a very simple example that works exactly how you want it (based on your question):
function disable() {
document.getElementById("demo").style.display = "none";
}
<div id="demo">
<button onclick="disable()">
Click Me
</button>
<h3>
This is part of the div
</h3>
</div>
I have many <p>s with the same function.
document.getElementById("minus").onclick = function() {
functionHide()
};
function functionHide() {
document.getElementById("plus").style.display = "block";
document.getElementById("minus").style.display = "none";
}
document.getElementById("plus").onclick = function() {
functionShow()
};
function functionShow() {
document.getElementById("plus").style.display = "none";
document.getElementById("minus").style.display = "block";
}
#plus {
display: none;
cursor: pointer;
}
#minus {
cursor: pointer;
}
.floatright {
float: right
}
.w50 {
width: 50%;
text-align: center;
}
<div class="w50">
<p>What paperwork do I need to complete to file for divorce ?
<span class="floatright inlineb" id="minus">- </span>
<span class="floatright inlineb" id="plus">+</span>
</p>
<p>How do I change my custody and suport orders ?
<span class="floatright inlineb" id="minus">- </span>
<span class="floatright inlineb" id="plus">+</span>
</p>
</div>
When I click on the first minus ( "-" ) it works correctly.
but for the second, it doesn't work.
I want to know how can I automatically chain for all others divs. they have the same typing code.
Also, I would know how can I change the last element (" - ") when an another + is clicked?
Here is a preview of what I want to do
And a fiddle: https://jsfiddle.net/khrismuc/prsebqg3/15/
You are using duplicate IDs, which is a no-no. Here is an example using classes and .querySelectorAll.
var minuses = document.querySelectorAll(".minus");
var pluses = document.querySelectorAll(".plus");
minuses.forEach(function(minus) {
minus.addEventListener('click', functionHide);
});
pluses.forEach(function(plus) {
plus.addEventListener('click', functionShow);
});
function functionHide() {
pluses.forEach(function(plus) {
plus.style.display = "block";
});
minuses.forEach(function(minus) {
minus.style.display = "none";
});
}
function functionShow() {
pluses.forEach(function(plus) {
plus.style.display = "none";
});
minuses.forEach(function(minus) {
minus.style.display = "block";
});
}
You can modify for your particular uses.
Your logic needs to be slightly more complex:
var current = -1;
function handleClick(clicked) {
$(".w50 p").removeClass("active").find("span").text("+");
$("#box p").hide();
if (current === clicked) {
current = -1;
return;
}
current = clicked;
$(".w50 p").eq(current).addClass("active").find("span").text("-");
$("#box p").eq(current).show();
}
$(document).ready(function() {
$(".w50 p").each(function(i, el) {
$(this).append($("<span>").text("+"));
$(this).click(function() {
handleClick(i);
});
});
$(".w50 p").eq(0).click();
});
.w50 {
width: 80%;
text-align: center;
}
.w50 p {
cursor: pointer
}
.w50 p.active {
color: orange
}
.w50 p span {
float: right;
width: 1em;
display: inline-block;
}
#box {
background-color: orange;
margin: 20px;
min-height: 6em;
}
#box p {
display: none;
padding: 1em
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="w50">
<p>What paperwork do I need to complete to file for divorce?</p>
<p>How do I change my custody and support orders?</p>
</div>
<div id="box">
<p>Paperwork description</p>
<p>Custody description</p>
</div>
I've next code:
$(function () {
$('#delete-button').click(function () {
deleteElementsBelow('#parent-container', 'element-2');
});
function deleteElementsBelow(parentContainerSelector, deleteBelowSelector) {
var deleteOthers = false;
$(parentContainerSelector).children().each(function () {
var $elem = $(this);
if (deleteOthers) {
$elem.remove();
} else if ($elem.hasClass(deleteBelowSelector)) {
deleteOthers = true;
}
});
}
});
#parent-container div {
background-color: red;
width: 20px;
height: 20px;
margin: 10px;
}
#parent-container div:nth-child(2n) {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent-container">
<div class="element-1"></div>
<div class="element-2"></div>
<div class="element-3"></div>
<div class="element-4"></div>
<button id="delete-button" type="button">Delete</button>
</div>
Is it possible to do action deleteElementsBelow by native jQuery API?
You could use something like $(parentContainerSelector + " ." +deleteBelowSelector).nextAll("div").remove() to remove all div after the target element.
This will remove divs with class element-3 and element-4
$(function () {
$('#delete-button').click(function () {
deleteElementsBelow('#parent-container', 'element-2');
});
function deleteElementsBelow(parentContainerSelector, deleteBelowSelector) {
var deleteOthers = false;
$(parentContainerSelector + " ." +deleteBelowSelector).nextAll("div").remove()
}
});
#parent-container div {
background-color: red;
width: 20px;
height: 20px;
margin: 10px;
}
#parent-container div:nth-child(2n) {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent-container">
<div class="element-1"></div>
<div class="element-2"></div>
<div class="element-3"></div>
<div class="element-4"></div>
<button id="delete-button" type="button">Delete</button>
</div>
Javascript report designer should allow to create copies of selected divs into same panel.
I tried to use
function DesignerClone() {
$(".ui-selected").each(function () {
var newDiv = $(this).prop('outerHTML'),
parentpanel = $(this).parent(".designer-panel-body");
parentpanel.prepend(newDiv);
});
}
but all divs are lost. and empty panel appears.
To reproduce, run code snippet and select some divs by mouse click.
After that press clone button.
How to clone boxes ?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<style>
.designer-panel-body {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.panel-footer {
background-color: inherit;
}
.designer-panel,
.designer-resetmargins {
margin: 0;
padding: 0;
}
.designer-verticalline,
.designer-horizontalline,
.designer-rectangle {
font-size: 1pt;
border: 1px solid #000000;
}
.designer-field {
border: 1px solid lightgray;
white-space: pre;
overflow: hidden;
}
.ui-selecting {
background-color: lightskyblue;
color: white;
}
.ui-selected {
background-color: lightskyblue;
border-color: darkblue;
color: white;
}
.designer-label {
white-space: pre;
}
.designer-field,
.designer-label {
font-family: "Times New Roman";
font-size: 10pt;
z-index: 2;
}
.designer-verticalline,
.designer-horizontalline,
.designer-rectangle,
.designer-field,
.designer-image,
.designer-label {
position: absolute;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
function DesignerClone() {
$(".ui-selected").each(function () {
var newDiv = $(this).prop('outerHTML'),
parentpanel = $(this).parent(".designer-panel-body");
parentpanel.prepend(newDiv);
});
}
function getpos(e) {
return {
X: e.pageX,
Y: e.pageY
};
}
function Rect(start, stop) {
this.left = Math.min(start.X, stop.X);
this.top = Math.min(start.Y, stop.Y);
this.width = Math.abs(stop.X - start.X);
this.height = Math.abs(stop.Y - start.Y);
}
$(function () {
var startpos;
var selected = $([]),
offset = {
top: 0,
left: 0
};
$(".designer-verticalline, .designer-rectangle, .designer-field, .designer-image").resizable();
var $liigutatavad = $(".designer-verticalline, .designer-horizontalline, .designer-rectangle, .designer-field, .designer-image, .designer-label");
$liigutatavad.draggable({
start: function (event, ui) {
var $this = $(this);
if ($this.hasClass("ui-selected")) {
// if this is selected, attach current offset
// of each selected element to that element
selected = $(".ui-selected").each(function () {
var el = $(this);
el.data("offset", el.offset());
});
} else {
// if this is not selected, clear current selection
selected = $([]);
$liigutatavad.removeClass("ui-selected");
}
offset = $this.offset();
},
drag: function (event, ui) {
// drag all selected elements simultaneously
var dt = ui.position.top - offset.top,
dl = ui.position.left - offset.left;
selected.not(this).each(function () {
var $this = $(this);
var elOffset = $this.data("offset");
$this.css({
top: elOffset.top + dt,
left: elOffset.left + dl
});
});
}
});
// ...but manually implement selection to prevent interference from draggable()
$(".designer-panel-body").on("click", "div", function (e) {
if ( /*!e.metaKey &&*/ !e.shiftKey && !e.ctrlKey) {
// deselect other elements if meta/shift not held down
$(".designer-panel-body").removeClass("ui-selected");
$(this).addClass("ui-selected");
} else {
if ($(this).hasClass("ui-selected")) {
$(this).removeClass("ui-selected");
} else {
$(this).addClass("ui-selected");
}
}
});
$(".designer-panel-body").selectable({});
});
</script>
</head>
<body>
<button type="button" class="btn btn-default" onclick="javascript:false;DesignerClone()">
<span class="glyphicon glyphicon-paste"></span>
</button>
<div class='panel designer-panel'>
<div class='panel-body designer-panel-body panel-warning' style='height:4cm'>
<div class='designer-field' contenteditable='true' style='top:2.30cm;left:5.84cm;width:10.24cm;height:0.63cm;font-family:Arial;font-size:14pt;font-weight:bold;'>vnimi+' '+dok.tasudok</div>
<div class='designer-field' contenteditable='true' style='top:2.30cm;left:16.37cm;width:2.68cm;height:0.61cm;font-size:14pt;'>DOK.kuupaev</div>
<div class='rectangle' style='border-width: 1px;background-color:#FFFFFF;top:2.99cm;left:1.34cm;width:18.05cm;height:5.29cm'></div>
<div class='designer-field' contenteditable='true' style='top:3.01cm;left:1.53cm;width:9.71cm;height:0.55cm;font-size:12pt;'>m.FIRMA</div>
<div class='designer-field' contenteditable='true' style='top:3.01cm;left:12.13cm;width:3.13cm;height:0.53cm;font-size:12pt;'>ise.telefon</div>
</div>
<div class='bg-warning'>
<div class='panel-footer'><i class='glyphicon glyphicon-chevron-up'></i> GroupHeader 1: str(dokumnr)+str(koopia,2)</div>
</div>
</div>
</body>
</html>
.appendTo takes selected element and removes it from previous position in the DOM.
jQuery.clone() is what you might be looking for.