Jasmine Jasmine - 29 days ago 10
Javascript Question

how to make element appear at the spot where mouse clicks in javascript

I want to start with a blank page, and when the user (mouse) clicks anywhere in the page, a box appears at that location.

This is what I have so far, I made the box hidden and then changed the style by adding an event listener but how do I create another event that allows the user to click anywhere, box appears, then click again in a different spot and another box appears in that location. -- using only vanilla Javascript

Thanks in advance, here's my html/css code:

<div id ="box"></div>

#box{
width:100px;
height:100px;
background-color: blue;
position: absolute;
visibility: hidden;
}


and Javascript code:

var box = document.getElementById("box");
addEventListener('click', function(){
box.style.visibility="visible";

});

Answer

You may get offsetX/Y or pageX/Y. Offset is relative to target element, page - relative to document

var box = document.getElementById("box");
   addEventListener('click', function(event){
     box.style.visibility="visible";
     box.left = event.pageX;
     box.top = event.pageY;
   });