H. J. H. J. - 1 year ago 79
HTML Question

Create an element on the clicked position?

I'm trying to create an element on the clicked position, and I figured out the following code. But nothing happened when I click on the page, and no errors were found in the console, Why?

function create(event) {
var i = document.createElement("img");
i.setAttribute("id", "a");
i.src = *imagefile*;
i.position = "absolute";
i.style.left = event.clientX+'px';
i.style.top = event.clientY+'px';
document.addEventListener("click", create);

Answer Source

A few issues

  1. You're creating the element, but you're not actually adding it anywhere. You need to make sure to append it to the dom with document.body.appendChild().
  2. i.position should be i.style.position as position is a CSS style.
  3. A minor nitpick. The 'id' attribute should be unique on a page. Clicking multiple times will make this not true. It's simply not needed in this scenario.

function create(event) {
  //Create the image
  var i = document.createElement('img');

  //Set the source of the image
  i.src = 'https://www.mozilla.org/media/img/styleguide/identity/firefox/guidelines-logo.7ea045a4e288.png';

  //Set CSS styles so it appears where you clicked (Top left corner)
  i.style.position = 'absolute';
  i.style.left     = event.clientX + 'px';
  i.style.top      = event.clientY + 'px';
  //Add it to the body of the document
//Main event listener for clicks
document.addEventListener('click', create);

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