Jasmine Jasmine - 17 days ago 5
Javascript Question

How to make element disappear once its created with event listener (pure Javascript)

I've been googling for hours and trying out different methods and can't get this to work.

I'm trying to do is: if there is no box, then add a box. If there is a box where you're clicking, then remove the box.

So far, it removes a box but automatically adds a new one, leaving a box on the screen when there should be none.

How do I get the box removed when someone clicks on it -- in pure Javascript.

Here is my jsfiddle so you can see what's happening. https://jsfiddle.net/on6z83ko/10/

Code:

addEventListener('click', createBox);

function createBox(event){

var box = document.createElement('div');

document.body.appendChild(box);

box.className = "box";
box.style.visibility="visible";
box.style.left = event.pageX + 'px';
box.style.top = event.pageY + 'px';

var mouse = event.currentTarget;
mouse.click = (mouse.click || 0) +1;

console.log(mouse.click);

box.addEventListener("click", function(){

var deleteBox = document.getElementsByClassName('box');

if(deleteBox){
box.remove();
}
});
}

Answer

Is this what you're looking for?

JSFiddle Example

This was the key-point:

if(target.classList.contains('box')){
    target.remove();
    }
Comments