0

I was looking for a div to follow up the mouse cursor, i've found solution here but the div now doesn't follow up the mouse while scrolling, any ideas?

<script type="text/javascript">

function getMouseCoords(e) {
var e = e || window.event;
document.getElementByTagName('body').innerHTML = e.clientX + ', ' + 
       e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
var s = document.createElement('div');
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '10px';
s.style.border = '1px solid black';
s.style.animationTime = "2.5s";
s.style.webkitTransform = "rotate(45deg)";
s.style.zIndex = "9999999999";

return {
init: function() {
  document.body.appendChild(s);
},

run: function(e) {
  var e = e || window.event;
  s.style.left  = (e.clientX - 15) + 'px';
  s.style.top = (e.clientY - 10) + 'px';
  getMouseCoords(e);
}
};
}());

window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}

</script>

i have no idea how to fix this at the moment, i just started studying, so any help would be appreciated.

DePaS
  • 59
  • 4

2 Answers2

0

Change the position from absolute to fixed. https://codepen.io/anon/pen/mXLLJK

s.style.position = 'fixed';
Karl Graham
  • 151
  • 4
  • thank you so much! now there is another problem, i can't click links with the div following the mouse, any suggestion? – DePaS Feb 21 '18 at 15:33
  • Have a look a the link below. it seems it an be done but there are some browser compatibility issues. https://stackoverflow.com/questions/3680429/click-through-a-div-to-underlying-elements – Karl Graham Feb 21 '18 at 15:38
0

With scrollTop you can sum the distance that user has scrolled down from the top:

document.documentElement.scrollTop

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

And you can add it in onscroll event:

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll

zelda11
  • 425
  • 2
  • 7