<div >
<button >Add div</button>
</div>
<div >
</div>
I've written a function that creates div in random colors and different locations at the click of a button. But I want each div I created to be deleted when clicked separately. How can I do this? Wrapper is my common div that everything in it
function RandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i ) {
color = letters[Math.floor(Math.random() * 16)];
}
return color;
}
function Top() {
return Math.floor((Math.random() * 700) 200) "px";
}
function Left() {
return Math.floor((Math.random() * 300) 200) "px";
}
function addDiv() {
var div = document.createElement("div");
div.className = 'box';
div.style.left = Left();
div.style.top = Top();
div.style.background = RandomColor();
document.querySelector('.wrapper').appendChild(div);
}
document.querySelector('button').addEventListener('click', addDiv);
CodePudding user response:
Is pretty simple, just add addEventListener
with remove
after appendChild
like:
function RandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i ) {
color = letters[Math.floor(Math.random() * 16)];
}
return color;
}
function Top() {
return Math.floor((Math.random() * 700) 200) "px";
}
function Left() {
return Math.floor((Math.random() * 300) 200) "px";
}
function addDiv() {
var div = document.createElement("div");
div.className = 'box';
div.style.left = Left();
div.style.top = Top();
div.style.background = RandomColor();
document.querySelector('.wrapper').appendChild(div);
div.addEventListener('click', (e) => {
e.target.remove();
});
}
document.querySelector('button').addEventListener('click', addDiv);
div{
width:50px;
height:50px;
display:inline-block;
}
<div class='wrapper'></div>
<button>pressme</button>
CodePudding user response:
Just add this line to your "addDiv" function:
div.onclick = function(){this.remove();};