Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positioning the div relative to mouse position

All,

How to Position the following div relative to mouse position so that the mouse and div are not out ofsync at theend of the page.May be just like a tooltip which always sjows the perfect 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>

Thanks........

like image 344
Hulk Avatar asked Feb 08 '10 03:02

Hulk


People also ask

How do I make a Div follow my mouse?

You can't follow the cursor with a DIV , but you can draw a DIV when moving the cursor! $(document). on('mousemove', function(e){ $('#your_div_id'). css({ left: e.

How do I map a mouse position in CSS?

For the start of the range, we get (n + #{10 * $i + 1}) , and for the end of the range we get (-n + #{10 * ($i + 1)}) . The mapping is done! When we hover over elements, --positionX and --positionY change according to the mouse position. That means we can use them to control the elements inside the .

What indicates the position of the mouse?

A cursor is a moving placement or pointer that indicates a position. It allows you to locate the current position of the mouse pointer on the screen and indicates where information can be entered or deleted.


1 Answers

You can try with this example,

$(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});  
});
like image 90
jumperchen Avatar answered Sep 30 '22 19:09

jumperchen