Create Div at Mouse Click

This is an example of how to create a div on the body at the location the user clicked on.

by Brandon Dixon

HTML

<body>

</body>

CSS

body {
  width: 100%;
  height: 100%;
  background-color: rgba(255,150,150,0.3);
}

.circle {
  border-radius: 50%;
  width: 100px;
  height: 100px;
  background-color: rgba(0,0,255,0.9);
  border: 2px solid black;
  position: absolute;
}

JavaScript

$(function() {
	console.log("script begins");
	$(document).on("click",function(e) {
  		console.log("Body clicked");
  
  		let x = e.pageX;
      let y = e.pageY;
      
      addCircle(x,y);
  });
});

/**
* Add a circle to the document and return its handle
*/
function addCircle(x,y) {
	let e = document.createElement('div');
  $(e).addClass("circle");
  
  let adjX = x - 50; //click happens in center
  let adjY = y - 50; 
  
  $(e).css("left",adjX);
  $(e).css("top",adjY);
  document.body.appendChild(e);
  return e;
}