I am trying to create a minimap feature, I have two HTML elements and these can be image or div, so when a user clicks on an element it should give/translate the coordinates of another target element.
The clicked element size (w/h) will always be small and the position will be absolute. so far I am succeeded to get clicked element position but I am not able to translate these coordinates into the target element.
CodePudding user response:
Map the coordinates using ratio of parent/child widths and heights
$(".child").click(function(e) {
var offset = $(this).offset();
var ratioX = $(".parent").width() / $(this).width();
var ratioY = $(".parent").height() / $(this).height();
var left = (e.pageX - offset.left) * ratioX;
var top = (e.pageY - offset.top) * ratioY;
var circle = $("<div />", {
class: 'circle'
});
$(circle).css({
left: left,
top: top
});
$(".parent").append(circle);
});
.parent {
border: 3px solid #000;
background: #898383;
width: 100%;
height: 300px;
}
.child {
background: #fff;
position: absolute;
right: 15px;
bottom: 40px;
width: 200px;
height: 100px;
border: 2px solid #eff431;
}
.circle {
width: 10px;
height: 10px;
background: red;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div >
child
</div>
</div>
<!-- some times the child element can be outside the parent element -->