Jasmine Jasmine - 1 year ago 90
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/


addEventListener('click', createBox);

function createBox(event){

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


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

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


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

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


Answer Source

Is this what you're looking for?

JSFiddle Example

This was the key-point:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download