I found this “div follows mouse” animation:
JSFiddle that belongs to the answer posted in: How to animate following the mouse in jquery.
var mouseX = 0, mouseY = 0;
$(document).mousemove(function(e){
mouseX = e.pageX;
mouseY = e.pageY;
});
// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.css({left:xp, top:yp});
}, 30);
I got quite intrigued by the inner workings and I tried to understand what the code is doing. I am currently learning javascript and I tried to replicate the “point to point” animation. I found this: Point to point animation algorithm, but it feels that the code of the original poster is pretty long and repetitive.
My current basic level of javascript is being an obstacle to fully understand the jQuery version (i still didn’t enter into the jQuery realm). Yet, I think that do this kind of animation in javascript might be possible, but the only way I can think about is with a code similar to the “point to point” link.
Can something like this be done with a code as short as the jQuery version? Or to do just javascript requires much longer routine?
Thanks for any suggestion or comment that you might have!
In this case, nearly, yes, because what’s being done is fairly simple and only a small amount of jQuery’s functionality is used. Specifically:
It’s hooking the
mousemoveevent ondocument, which can easily be done withaddEventListener(orattachEventon older versions of IE).It’s locating an element by
id($("#follower")), which can easily be done withgetElementById.It’s setting the
leftandtopof an element via jQuery’scssfunction. This can easily be done by setting theleftandtopproperties on the element’sstyleproperty.Putting that all together: Fiddle
As you can see, the biggest issue is hooking the event in a way that plays nicely with others. Although you could just use the
document.onmousemoveversion, that would clobber any othermousemovehandlers ondocument, which is why we first look foraddEventListenerorattachEvent.Some handy references, in roughly chronological order (latter ones update/supercede/add to earlier ones):
None of which should be taken to say that you can’t use a good library like jQuery, there are several good reasons to (the events thing above is just one example). But it’s always best to understand the basics as well, even if you use a library to avoid having to deal with them all that much.