I’m making some boxes move around randomly when the cursor is not over the div that contains them. They will only follow the mouse when it is “hovering” over div.
However I am trying to make the boxes revert to their random “default” movement after the mouseout. If the user scrolls over the div, then the images follow again. I know the function I am trying to use looks like this but somehow I can’t seem to make it work.
<script>
$(document).ready(function(){
$("(boxes ref)").mouseover(function(){
(follow cursor)
});
$("(boxes ref)").mouseout(function(){
(random movement)
});
});
</script>
Original code:
<!DOCTYPE html>
<html>
<head>
<style>
div#container {height:500px;width:500px;}
.a {
position:fixed;
}
.b {
position:fixed;
}
.c {
position:fixed;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
animateDiv($('.a'));
animateDiv($('.b'));
animateDiv($('.c'));
});
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv($target) {
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$target.animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv($target);
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.03;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
</script>
</head>
<body>
<div id="container">
<img src="https://preview.redd.it/u89vxytsqax41.png?auto=webp&s=fe77dd09acb7fd89a637da1b2da760cc9862dc07" alt="prgm" class='a' id='image'>
<img src="https://preview.redd.it/u89vxytsqax41.png?auto=webp&s=fe77dd09acb7fd89a637da1b2da760cc9862dc07" alt="prgm" class='b' id='image2'>
<img src="https://preview.redd.it/u89vxytsqax41.png?auto=webp&s=fe77dd09acb7fd89a637da1b2da760cc9862dc07" alt="prgm" class='c' id='image3'>
</div>
<script>
$(document).mousemove(function(e){
/*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
$("#image").stop().animate({left:e.pageX, top:e.pageY}, {duration: 5000});
});
</script>
<!-- make the images follow the cursor -->
<script>
$(document).mousemove(function(e){
/*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
$("#image2").stop().animate({left:e.pageX, top:e.pageY}, {duration: 5000});
});
</script>
<script>
$(document).mousemove(function(e){
/*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
$("#image3").stop().animate({left:e.pageX, top:e.pageY}, {duration: 5000});
});
</script>
</body>
</html>
Thanks