I am trying to create a jQuery script that allows a user of my webpage to select points on a exploded diagram where damage has occurred. I want it to show a cross when clicked, I have gotten it to work with this code:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#vehSelImg").on("click", function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
jQuery('#vehSelData').append("X Coord: " + x + ", Y Coordinate: " + y + "\n");
var cross = "<img style='position:absolute; height:20px; top:" + y + "px; left:" + x + "px;'" + " src='/content/x.png'/>"
jQuery('#vehSelDiv').append(cross);
});
});
</script>
However when I add this to my webpage with headers etc the crosses appear in the wrong location with an offset of the above elements, I know it's to do with event.pageX & Y but how do I account for other elements so that it overlays exactly where the user clicked?
EDIT: I've now came to a solution but I'm not a fan of the workaround if anyone can assist?
jQuery(document).ready(function(){
const coordAr = new Array();
jQuery("#vehSelImg").on("click", function(event) {
var elemRect = document.getElementById('vehSelImg').getBoundingClientRect();
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
var offsetX = x + Math.round(elemRect.left) - 25;
var offsetY = y + Math.round(elemRect.top) - 25;
console.log(elemRect);
coordAr.push(x+", " + y);
jQuery('#vehSelData').append("X Coord: " + offsetX + ", Y Coord: " + offsetY + "\n");
var cross = "<img style='position:absolute; height:20px; top:" + offsetY + "px; left:" + offsetX + "px;'" + " src='/content/x.png'/>"
jQuery('#vehSelDiv').append(cross);
});
jQuery('button').on("click", function(event) {
console.log(coordAr);
jQuery('#vehSelData2').text(coordAr);
});
});
Thanks for your time!
Curtis