I have a page where I want to dynamically add a pin/marker wherever I clicked.
I’ve tried
JavaScript
x
13
13
1
$("body").click(function(e) {
2
3
console.log("%c ______________________________", "background: linear-gradient(45deg, red, yellow, blue, green, purple)");
4
console.log("e.pageX", e.pageX);
5
console.log("e.pageY", e.pageY);
6
7
8
9
// var pin = .css("position", "absolute").css("top", e.pageY).css("left", e.pageX);
10
$("body").append('<i class="fa fa-location"></i>');
11
12
13
});
JavaScript
1
3
1
html,body{
2
height:100%;
3
}
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I couldn’t get it to work.
Advertisement
Answer
Create the element, apply the styles, then append.
Also, make sure the element has a higher z-index
:
JavaScript
1
4
1
$("body").click(function(e) {
2
const pin = $('<i class="fa fa-location"></i>').css("position", "absolute").css("top", e.pageY).css("left", e.pageX)
3
$("body").append(pin)
4
});
JavaScript
1
8
1
html,
2
body {
3
height: 100%;
4
}
5
6
i{
7
z-index:10000;
8
}
JavaScript
1
1
1
<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>