Reputation: 1582
I have a setup where divs follow the cursor around the screen (currently 2 divs but this will be content managed so there's soon to be dozens of them), ideally each div following the cursor at a different speed (with a maximum speed of 50).
jsfiddle: http://jsfiddle.net/neal_fletcher/nEKgN/
jQuery:
$( document ).ready(function() {
var mouseX = 0, mouseY = 0;
$(window).mousemove(function(e){
mouseX = Math.min(e.pageX);
mouseY = Math.min(e.pageY);
});
var follower = $(".stuck");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// higher is slower
xp += (mouseX - xp) / 30;
yp += (mouseY - yp) / 30;
follower.css({left:xp, top:yp});
}, 30);
});
$( document ).ready(function() {
var mouseX = 0, mouseY = 0;
$(window).mousemove(function(e){
mouseX = Math.min(e.pageX);
mouseY = Math.min(e.pageY);
});
var follower = $(".stuck-2");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// higher is slower
xp += (mouseX - xp) / 20;
yp += (mouseY - yp) / 20;
follower.css({left:xp, top:yp});
}, 30);
});
In the example above I've had to give each div a different class (or ID) to set a different speed for each one, but like I say as this is going to be content managed this will be impossible, ideally I'd like all the divs to have the same class and randomize the speed for every one, with a maximum speed of 50. Can't figure out if this is at all possible? Any suggestions would be greatly appreciated!
Upvotes: 1
Views: 128
Reputation:
Use .each
to iterate over the followers and assign each a "jump" value:
$(document).ready(function () {
var mouseX = 0,
mouseY = 0;
$(window).mousemove(function (e) {
mouseX = Math.min(e.pageX);
mouseY = Math.min(e.pageY);
});
var followers = $(".stuck");
followers.each(function () {
var follower = $(this),
jump = 1 + (Math.random() * 50),
xp = 0,
yp = 0;
var loop = setInterval(function () {
// higher is slower
xp += (mouseX - xp) / jump;
yp += (mouseY - yp) / jump;
follower.css({
left: xp,
top: yp
});
}, 30);
});
});
Here is a demonstration: http://jsfiddle.net/Nxdm7/
Upvotes: 4