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

background-color: blue;
position: absolute;
visibility: hidden;

and Javascript code:

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


Answer Source

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.left = event.pageX;
     box.top = event.pageY;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download