Positioning div relative to mouse position

All,

How to place the next div relative to the position of the mouse so that the mouse and div do not exit the synchronous transition on the page. Perhaps it will be like a hint that always gives an ideal position at the end of the page.

<style type="text/css">
#div1 { width: 200px; height: 30px; background-color: #a9a9a9; color: #fff; position: absolute; }
 </style>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$(window).mouseover(function(event){
$("#div1").css({'top': event.pageY, 'left': event.pageX});  
});
});
</script>
<div id="div1">mouseover me</div>

Thank........

+5
source share
1 answer

In this example, you can try,

$ (window) .mouseover (function (event) {
    var x = event.pageX,
        y = event.pageY,
        scX = $ (window) .scrollLeft (),
        scY = $ (window) .scrollTop (),
        scMaxX = scX + $ (window) .width (),
        scMaxY = scY + $ (window) .height (),
        wd = $ ("# div1"). width (),
        hgh = $("#div1").height();

    if (x + wd > scMaxX) x = scMaxX - wd;
    if (x < scX) x = scX;
    if (y + hgh > scMaxY) y = scMaxY - hgh;
    if (y < scY) y = scY;
    $("#div1").css({'top': y, 'left': x});  
});
+6

All Articles