Search code examples
javascriptjquerycss

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!
This it the example fiddle I got the JS from: http://jsfiddle.net/hj57k/


Solution

  • 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>