Incorrect mouse x y position on Bootstrap Modal window

Viewed 1804

I am trying to get the x and y co-ordinates inside a Modal window setup using Bootstrap. Modal window pops up on click of the image but when i click anywhere on the Modal window it gives me co-ordinates relative to the browser window and not the Modal window.

HTML:

<div style="width: 200px; height: 200px;background-color: red; margin: 200px 
auto">
  <img src="image/Chrysanthemum.jpg" width="100%" height="100%" alt="">  
</div>



<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog" >
<!-- Modal content-->
<div class="modal-content" style="width: 700px; height: 600px">

  <div class="modal-body">
    <img src="" alt="" id="modal-img" width="100%" height="100%">
  </div>

</div>

JQuery:

 $("img").on("click",(function(){

    var imgsrc = $(this).attr("src");             
      $("#modal-img").attr("src",imgsrc);
      $("#myModal").modal("show");     
}));



$("#myModal").on("click",function(e){
  var relativeX = e.pageX - this.offsetLeft;
  var relativeY = e.pageY - this.offsetTop;
   alert(relativeX + " " + relativeY);  
});
1 Answers

Your #myModal element is the full width background of the modal, so it's always going to have 0 for offsetTop and offsetLeft; what you want is to target the dialogue within the background instead.

$("#myModal").on("click",function(e){
  var dialogElm = $("#myModal .modal-dialog");
  var relativeX = e.pageX - dialogElm.offset().left;
  var relativeY = e.pageY - dialogElm.offset().top;
   alert(relativeX + " " + relativeY);  
});
Related