How to let a Div stick to cursor
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>
sticking a div to mouse cursor doesn't work
As others have mentioned, the syntax is getElementById
instead of getElementsById
.
Also, it seems that you are trying to set offsetTop
and offsetLeft
by reference. First, offsetLeft
and offsetTop
are read-only. Second, changing a variable that has been set to a element's property will not change the value of the property itself.
I had success by setting a CSS definition directly, using style
:
var mydiv1=document.getElementById("myDiv1");
document.addEventListener('mousemove', function (e) {
var x = e.pageX;
var y = e.pageY;
mydiv1.style.top = y + 'px';
mydiv1.style.left = x + 'px';
});
WORKING EXAMPLE
Edit:
You can tweak the position of the <div>
relative to the mouse position by adding to or subtracting from the x
and y
values. For example:
mydiv1.style.top = (y-15)+ 'px';
mydiv1.style.left = (x-8) + 'px';
WORKING EXAMPLE
How to attach div to mouse pointer so it will work properly during scrolling
You need to use e.clientX
and e.clientY
in this mannertop: e.clientY+$(this).height()
and left: e.clientX+$(this).width()/2
for bottom center of this
element in scope. You can add anything else wrt the current element hovered upon
e.clientX
and e.clientY
will provide the exact mouse co-ordinates
Snippet Below
$('button').mouseenter(function (e) { var data = $(this).data('value'); if(data){ $('<div />', { 'class' : 'tip', text : $(this).data('value'), css : { position: 'fixed', top: e.clientY+$(this).height(), left: e.clientX+$(this).width()/2 } }).appendTo(this);}}).mouseleave(function () { $('.tip', this).remove(); }).mousemove(function (e) { $('.tip', this).css({ top: e.clientY+$(this).height(), left: e.clientX+$(this).width()/2 }); })
button {margin: 10px;}.divs { width: 100%; height: 350px; background-color: #ddd; margin: 0px;}.tip { border: 1px solid #eee; background: #fff; box-shadow: 3px 4px 6px rgba(0,0,0,0.4); padding: 3px; font-weight: bolder;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div class="divs"></div> <button data-value="Per">First</button> <button data-value="Aspera">Second</button> <button data-value="Ad">Third</button><br> <button data-value="Astra">Yadi</button> <button data-value="To infinity">Yada</button> <button data-value="and beyond!">Bla-bla</button><div class="divs"></div>
Show DIV at mouse cursor on hover of span
You're pretty much there:
function hoverdiv(e,divid){
var left = e.clientX + "px"; var top = e.clientY + "px";
var div = document.getElementById(divid);
div.style.left = left; div.style.top = top;
$("#"+divid).toggle(); return false;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="divtoshow" style="position: fixed;display:none;">test</div> <br><br> <span onmouseover="hoverdiv(event,'divtoshow')" onmouseout="hoverdiv(event,'divtoshow')">Mouse over this</span>
Attemping to get a div to follow cursor on mousemove, but with a delay
I did it slightly differently. Instead of using setInterval
(or even setTimeout
) - I just made the animation take x amount of milliseconds to complete. The longer the animation, the less responsive the following div will seem to be.
The only problem I notice is that it gets backed up if the mouse is moved a lot.
$(document).ready(function () {
$("body").mousemove(function (e) {
handleMouseMove(e);
});
function handleMouseMove(event) {
var x = event.pageX;
var y = event.pageY;
$("#cube").animate({
left: x,
top: y
}, 1);
}
});
https://jsfiddle.net/jvmravoz/1/
jQuery: mouse following element wont stick with cursor when scrolling
In onPointerMove
, try replacing:
const { clientX: x, clientY: y } = pointer;
with:
const { pageX: x, pageY: y } = pointer;
Here's a good post explaining the differences between these values:
https://stackoverflow.com/a/9335517/965834
Also, change:
target.x = rect.left + (rect.width >> 1);
target.y = rect.top + (rect.height >> 1);
into:
target.x = window.scrollX + rect.left + (rect.width >> 1);
target.y = window.scrollY + rect.top + (rect.height >> 1);
This takes into account scrolling when calculating the position of your buttons.
Demo:
const windowW = window.innerWidth;const windowH = window.innerHeight;const maxLength = Math.max(windowW, windowH);
const cursorWidth = 100;const cursorR = cursorWidth >> 1;const cursorDelay = 10;
const buttons = Array.from(document.querySelectorAll('.border-button'));
const cursor = { el: document.querySelector('.border-cursor'), x: windowW >> 1, y: windowH >> 1, scaleX: 1, scaleY: 1,};
const target = { x: windowW >> 1, y: windowH >> 1, width: cursorWidth, followMouse: true,};
const norm = (val, max, min) => (val - min) / (max - min);const toDegrees = r => r * (180 / Math.PI);const distanceBetween = (v1, v2) => Math.sqrt((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y +- v2.y));
const loop = () => { const destX = target.x - cursorR; const destY = target.y - cursorR;
const newX = cursor.x + ((destX - cursor.x) / cursorDelay); const newY = cursor.y + ((destY - cursor.y) / cursorDelay); const angle = angleBetween(cursor.x, cursor.y, newX, newY);
if (target.followMouse) { const distance = Math.abs(distanceBetween(target, cursor)); const scale = norm(distance, maxLength, cursorR); cursor.scaleX = 1 + scale; cursor.scaleY = 1 - scale; } else { const targetScale = target.width / cursorWidth;
cursor.scaleX += (targetScale - cursor.scaleX) / (cursorDelay / 2); cursor.scaleY = cursor.scaleX; }
cursor.x = newX; cursor.y = newY;
cursor.el.style.transform = `translate(${cursor.x}px, ${cursor.y}px) rotate(${toDegrees(angle)}deg) scale(${cursor.scaleX}, ${cursor.scaleY})`;
requestAnimationFrame(loop);};
const angleBetween = (x1, y1, x2, y2) => Math.atan2(y2 - y1, x2 - x1);
const onPointerMove = (e) => { if (!target.followMouse) { return; }
const pointer = (e.touches && e.touches.length) ? e.touches[0] : e; const { pageX: x, pageY: y } = pointer;
target.x = x; target.y = y;};
const onPointerOver = (e) => { const btn = e.target; const rect = btn.getBoundingClientRect();
target.followMouse = false; target.x = window.scrollX + rect.left + (rect.width >> 1); target.y = window.scrollY + rect.top + (rect.height >> 1);
target.width = Math.max(rect.width, rect.height) + 50;};
const onPointerOut = () => { target.followMouse = true; target.width = cursorWidth;};
document.body.addEventListener('mousemove', onPointerMove);document.body.addEventListener('touchmove', onPointerMove);
buttons.forEach((btn) => { btn.addEventListener('touchstart', onPointerOver); btn.addEventListener('mouseover', onPointerOver);
btn.addEventListener('touchend', onPointerOut); btn.addEventListener('mouseout', onPointerOut);});
loop();
html,body { margin: 0; padding: 0;}
.wrapper { width: 100vw; min-height: 1500px; display: flex; flex-direction: row; align-items: center;}
.container { width: 100%; display: flex; padding: 0 1rem;}
.cursor { position: absolute; z-index: 10; width: 100px; height: 100px; border: 2px solid #23bfa0; border-radius: 50%;
pointer-events: none;}
.button { padding: 1rem;
background-color: #23bfa0; border: none; box-shadow: 0 0 7px 0px rgba(0, 0, 0, 0.2);
color: white; font-size: 1.2rem;
cursor: pointer;
transition: box-shadow 0.1s ease-in, transform 0.1s ease-in; &--small { padding: 0.75rem; font-size: 0.75rem; } &:hover { transform: translate(0%, -2px); box-shadow: 0px 4px 9px 2px rgba(0, 0, 0, 0.2) }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body><div class="cursor border-cursor"></div>
<div class="wrapper"> <div class="container"> <button class="button button--small border-button">small</button> <button class="button border-button">hover me</button> <button class="button border-button">hover me more</button> </div></div></body>
Cursor-following div - Disappears when mouse moves down or right
Basically if your mouse moves over the .hover
overlay, it generates a hover "out" on the item underneath your mouse. Moving the mouse left/right causes the cursor to move on and off the overlaid div.
Add pointer-events: none;
to your .hover
style. This will stop it being visible to the mouse and avoid generating any events on the .hover
:
http://jsfiddle.net/4ba70vy3/6/
.hover {
pointer-events: none;
display: none;
position: absolute;
float: left;
font-family: Calibri, sans-serif;
font-size: 0.7em;
background-color: rgb(255, 255, 230);
border: 1px solid black;
-webkit-box-shadow: 0 0 2px rgba(0, 0, 0, 0.4);
box-shadow: 0 0 2px rgba(0, 0, 0, 0.4);
padding: 1px 3px;
z-index: 50;
}
Update: If the .hover was below the mouse, vertical movement would cause the same problem.
http://jsfiddle.net/4ba70vy3/7/
Also, as DevlshOne
suggests, you might as well use the title=
attribute on the controls and maybe just do yours for older browsers?
Related Topics
JavaScript How to Check User Agent for Mobile/Tablet
Semantic-Ui Modal Size Keeps Extending to the Height of a Page
How to Change the Viewport Meta Tag in Mobile Safari on the Fly
Changing Background Color of a Specific Row in Slickgrid
Gulp with Gulp-Ruby-Sass: Error: ../Style.Css.Map:3:1: Unknown Word
Iframe CSS Override for New Twitter Widget
Jquery UI Datepicker: Don't Highlight Today When It Is Also Selected
List of All Background Images in Dom
CSS in My JavaScript Widget Colliding with Target Page CSS
Scrolling Log File (Tail -F) Animation Using JavaScript
Dynamically Modify Webkit Animation with JavaScript
Is There Js Plugin Convert the Matrix Parameter to CSS3 Transform Property
React Animation for Moving an Element from One Parent to Another
Animate CSS3 Gradient-Positions Using Jquery