Haq.H Haq.H - 4 months ago 34
jQuery Question

Create a circle at mouse location on mouse move

I am attempting to code a custom mouse trail. To do this I am using temporary divs that appear at the mouse location and fade out after a small interval. Currently the divs only appear at mouse location. I am trying to make them appear at where the mouse is at the moment and stay there while the mouse moves on and draws more divs. Also, how would I add a fade out effect to each individual div so after being placed it would slowly go transparent.

Here's my code so far.



var posX,
posY,
paused = null,
circles = [],
maxCircles = 30,
//width & height of div
circleSize,
//border radius to make it look like a circle
rad,
randCircle;

$(document).ready(function() {
for (var i = 0; i < maxCircles; i++) {
circleSize = Math.floor((Math.random() * 10) + 5);
rad = Math.floor(circleSize / 2);
circles[i] = document.createElement("Div");
circles[i].style.opacity = "0.6";
circles[i].className = "circle";
circles[i].style.width = circleSize + "px";
circles[i].style.height = circleSize + "px";
circles[i].style.borderRadius = rad + "px";
circles[i].style.background = "green";
circles[i].style.zIndex = "-1";
}
$("body").mousemove(function(e) {
posX = e.clientX - 5;
posY = e.clientY - 5;
randCircle = Math.floor((Math.random() * (maxCircles - 1)) + 0);
if (!paused) {
document.getElementsByTagName("body")[0].appendChild(circles[randCircle]);

$('.circle').css({
position: "absolute",
top: posY,
left: posX
});

paused = setTimeout(function() {
paused = null
}, 100);
}
});
});

body, html {
height: 100%;
background: #eee;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>




Answer

Your divs change position because you're setting the position of every div with the class name "circle".

You need to change

$('.circle').css({position:"absolute", top:posY,left:posX});

To

circles[randCircle].css({position:"absolute", top:posY,left:posX});

To make them fade out you could add an animation to the circles using CSS.