Skip to content
Advertisement

Dynamically append DOM where mouse clicked

I have a page where I want to dynamically add a pin/marker wherever I clicked.

I’ve tried

$("body").click(function(e) {

  console.log("%c ______________________________", "background: linear-gradient(45deg, red, yellow, blue, green, purple)");
  console.log("e.pageX", e.pageX);
  console.log("e.pageY", e.pageY);



  // var pin = .css("position", "absolute").css("top", e.pageY).css("left", e.pageX);
  $("body").append('<i class="fa fa-location"></i>');


});
html,body{
  height:100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I couldn’t get it to work.

enter image description here

Advertisement

Answer

Create the element, apply the styles, then append.

Also, make sure the element has a higher z-index:

$("body").click(function(e) {
  const pin = $('<i class="fa fa-location"></i>').css("position", "absolute").css("top", e.pageY).css("left", e.pageX)
  $("body").append(pin)
});
html,
body {
  height: 100%;
}

i{
  z-index:10000;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer" /><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement