Jasmine
Jasmine

Reputation: 17

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";

      });

Upvotes: 1

Views: 2201

Answers (2)

blex
blex

Reputation: 25659

You can use event.pageX and event.pageY to get the cursor position relative to the document top-left corner. Try it below:

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';
  document.body.appendChild(box);
}
.box {
  padding: 10px;
  margin-left: -10px;
  margin-top: -10px;
  background-color: blue;
  position: absolute;
}
<p>Click anywhere!</p>

Also note that if you want to have multiple boxes, it is best to use a class rather than an ID. An ID is meant to reference a unique element, whereas a class is meant to be shared among multiple ones.

Upvotes: 1

Oleg Imanilov
Oleg Imanilov

Reputation: 2751

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;
   });

Upvotes: 1

Related Questions