Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let a Div stick to cursor

I have a script that shows a div on hover and sticks it to the cursor.

$(".picture_holder_thumb").mouseover(function () {
    $(".title", this).show();
});

$(".picture_holder_thumb").mouseout(function () {
    $(".title", this).hide();
});
$(document).bind('mousemove', function (e) {
    $(".title", this).css({
        left: e.pageX,
        top: e.pageY
    });
});

It works, but somehow there's always very much space between the sticky div and the cursor.

This is my Div's CSS:

#img-container .captioning .title {
    width: auto;
    height:auto;
    position: absolute;
    float:left;
    z-index:1;
    display: none;
}

Is there something wrong with my JS? I am thankful for any help!

Here you can see it live with the problem: http://www.cyrill-kuhlmann.de/index.php/projects


This it the example fiddle i got the JS from: http://jsfiddle.net/hj57k/

like image 737
Cyrill Avatar asked Sep 19 '14 13:09

Cyrill


People also ask

How do you make a Div follow the cursor?

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.

What is the cursor property in CSS?

The cursor CSS property sets the mouse cursor, if any, to show when the mouse pointer is over an element.

How do I move cursor in HTML?

To do this, we use document. elementFromPoint(x+px, y+py) in which we pass the position of image cursor. This will gives us the object of the element, the image cursor is on. After obtaining the required object, we can invoke the object.


1 Answers

Here is a nice pure javascript and easy way to make a div stick to the cursor pointer.

document.addEventListener('mousemove', function(ev){
    document.getElementById('acab').style.transform = 'translateY('+(ev.clientY-80)+'px)';
    document.getElementById('acab').style.transform += 'translateX('+(ev.clientX-100)+'px)';            
},false);
#acab {
  position: fixed; /* Floating above */
  transition: transform 0.23s; /* Sticking effect */
  pointer-events: none; /* Allow clicking trough the div */
}
button {cursor: pointer}
<div id="acab">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/Anarchist_black_cat.svg/150px-Anarchist_black_cat.svg.png">  </img>
</div>

<!-- A button, to test a mouse click -->
<button onclick="document.body.style.background=['red','green','grey','purple','magenta'][~~(Math.random()*5)]">Test click!</button>
like image 155
NVRM Avatar answered Oct 20 '22 00:10

NVRM