Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Keep the cursor in the center of an image while the image follows

I have a stage (id="box"), when the cursor moves on this stage, a red circle will moves along with the cursor. Everything works as expects, but the cursor is outside of the red circle.

I try to get the cursor stays in center the circle, but not successful, yet.

Any help would be appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$("#box").mousemove( function(e) {
  $popup = $(this).find(".circle").first();
  var eTop = $(this).offset().top;
  var eLeft = $(this).offset().left; 
  var x = e.pageX;
  var y = e.pageY;
 // console.log("pageX: " + x);
 //  console.log("pageY: " + y)
  $(this).find(".circle").css({top: y - eTop, left: x - eLeft });

});
#box {
  width:500px;
  height:200px;
  display:block;
  background: green;
  position:relative;

}


.circle {
      position: absolute;
    z-index: 100;
    overflow:hidden;
    white-space: nowrap;
    border: 1px solid red;
    width: 100px;
    height: 100px;
    border-radius: 100%
}

#box .circle {visibility: hidden;}
#box:hover .circle {visibility: visible;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<div id="box">
    <div class="circle"></div>
    </div>

>Solution :

You forgot to subtract the circle radius from its coordinates:

$("#box").mousemove( function(e) {
  $popup = $(this).find(".circle").first();
  var eTop = $(this).offset().top;
  var eLeft = $(this).offset().left; 
  var x = e.pageX;
  var y = e.pageY;
 // console.log("pageX: " + x);
 //  console.log("pageY: " + y)
  $(this).find(".circle").css({top: y - eTop - 50, left: x - eLeft - 50});

});
#box {
  width:500px;
  height:200px;
  display:block;
  background: green;
  position:relative;

}


.circle {
      position: absolute;
    z-index: 100;
    overflow:hidden;
    white-space: nowrap;
    border: 1px solid red;
    width: 100px;
    height: 100px;
    border-radius: 100%
}

#box .circle {visibility: hidden;}
#box:hover .circle {visibility: visible;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<div id="box">
    <div class="circle"></div>
    </div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading