My goal is to determine the position of an x and y location when a user clicks on an image. This information will be used to add a spot to the image that displays relevant information. The content for the spot will be dynamically loaded from a SQL database, but my current focus is on getting the positioning right.
I've searched on Stack Overflow and found suggestions to use e.pageX - element.offsetLeft
for the x location and e.pageY - element.offsetTop
for the y location. However, when I tried placing a div with coordinates like
<div style="position: absolute; top: 253px; left: 50px;"></div>
, it didn't appear where I expected it to be. The left coordinate represents the x position and the top coordinate represents the y position.
To summarize, here's what I'm trying to accomplish:
- A lightbox should appear in the middle of the screen with the selected image displayed.
- When users click on the image, the x and y coordinates are calculated and then used to position an element using CSS exactly where they clicked on the image.
var $imgCont = $('#img-wrap'),
$img = $('#img')
$img.click(function(e) {
var pos = {
left: e.pageX - $img.offset().left,
top: e.pageY - $img.offset().top
}
$('<div class="box">').css(pos).appendTo($imgCont)
})
#img-wrap {
position: absolute;
background-color: rgba(0,0,0,.7);
width: 100%;
height: 100%;
top: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 16px;
height: 16px;
position: absolute;
background: red;
z-index: 100
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click image to add boxes</p>
<div id="img-wrap">
<img id='img' src=http://via.placeholder.com/400x400 ">
</div>