I'm trying to make a box copier that creates boxes which each contain a button to delete itself. Each box is a duplicate of a hidden template box, and each has an id starting at box1:
This is what I have so far:
let boxcount = 0;
function removebox() {
this.parentNode.remove();
}
function addbox() {
var container = document.getElementById("container"),
box = document.getElementById("boxoriginal");
var boxcopy = box.cloneNode(true);
boxcount += 1;
boxcopy.id = "box" + boxcount;
container.appendChild(boxcopy);
var remover = document.createElement("DIV");
remover.innerHTML = "x";
remover.onclick = removebox;
document.getElementById(boxid).appendChild(remover);
}
The problem is that if I click on the X in box1 for instance, it removes the last box just added, rather than box1. I've tried something similar using EventListener but with the same result.
I'm brand new to JS, so I can only guess that I'm misunderstanding how this works.
Maybe not a perfect solution for what you are trying to achieve, but you might want to create a structure more like:
let doc, bod, M, I, SimpleBoxMaker; // for use on other loads
addEventListener('load', ()=>{
doc = document; bod = doc.body; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
SimpleBoxMaker = function(appendTo = bod){
this.container = M('div');
this.addBox = contentNode=>{
const container = this.container, box = M('div'), x_div = M('div');
box.className = 'box_div'; x_div.className = 'x_div'; x_div.innerHTML = '×';
box.appendChild(x_div);
if(contentNode)box.appendChild(contentNode);
x_div.onclick = ()=>{
box.remove();
}
container.appendChild(box);
return this;
}
appendTo.appendChild(this.container);
}
// below code can be put on a separate page using a `load` Event (besides // end load line)
const bigBox = new SimpleBoxMaker, addBox = I('add_box');
addBox.onclick = ()=>{
const div = M('div');
div.textContent = 'Before adding this node there were '+bigBox.container.children.length+' children in the container';
bigBox.addBox(div);
}
}); // end load
*{
box-sizing:border-box:
}
.box_div{
min-height:30px; border:1px solid #000; margin-top:2px;
}
.x_div{
cursor:pointer; display:flex; justify-content:center; align-items:center; width:30px; height:30px; background:#900; color:#fff; font:bold 24px san-serif; text-align:center; float:right;
}
<button id='add_box'>Add Box</div>