user18134288
user18134288

Reputation:

Random div generator with javascript

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

Upvotes: 0

Views: 254

Answers (2)

Kevin K Varughese
Kevin K Varughese

Reputation: 346

Just add this line to your "addDiv" function:


    div.onclick = function(){this.remove();};

Upvotes: 0

Simone Rossaini
Simone Rossaini

Reputation: 8162

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>

Upvotes: 1

Related Questions