Generate a circular shape wherever the mouse is moved

I'm currently working on implementing a custom mouse trail using temporary divs. These divs are supposed to appear at the location of the mouse and then fade out after a short period. However, I've run into an issue where the divs only appear at the initial mouse location and don't follow the mouse as it moves. I am trying to figure out how to make the divs stick with the mouse as it moves and continue drawing more divs along the path. Additionally, I would like to add a fade-out effect to each individual div so that they gradually become transparent after being placed. Here is the code snippet I have written 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 №1

The positioning of your divs is being affected because you're specifically targeting all divs with the class "circle".

A solution would be to update your code from:

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

To:

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

If you want them to fade out, consider adding a CSS animation to the circles.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

obtaining data from a JSON object in Node.js

Retrieve response in function node.js [ { instrument_token: '12598786', exchange_token: '49214', tradingsymbol: 'AARTIIND21JAN1000CE', name: 'AARTIIND' }, { instrument_token: '125998 ...

Reverse lookup and deletion using Mongoose

Currently, I am attempting to perform a health check on the references within one of my collections. The goal is to verify if objects being referenced still exist, and if not, remove that particular _id from the array. Despite my efforts, I have not come ...

When I apply properties in JavaScript, I find that I am unable to utilize the CSS "hover" feature

For a personal project I am currently working on, I decided to experiment with setting background colors using Javascript. However, I have encountered an issue where my CSS code that changes the hover property does not seem to work after implementing the J ...

The webpage becomes unresponsive and gets stuck when sending a stream of requests to the web server via ajax

I am currently working on creating a signal on the webpage that displays either a green or red color based on values retrieved from a database. However, when I send a request after 10 seconds, the page appears to freeze and becomes unresponsive. I am strug ...

"jQuery now has the ability to delete multiple items at once, setting it

One interesting feature I have implemented is a table that contains buttons which appear when you hover over its rows. Specifically, there is a delete button that triggers a custom confirm dialog box; this dialog simply accepts a callback function to execu ...

What is the best way to break out of a for ... each loop and method simultaneously?

I have a function that iterates over select options in the code snippet below. I am checking if the value of the option has already been entered. While it escapes from the for-each loop, it doesn't exit from the method. yeniIlacBagla_ilacBagla: funct ...

Is it possible to create a popup without using JavaScript?

Is it feasible to create a popup window without utilizing JavaScript by using the href tag or a similar method? For example, could something like <a href="popup:http://stackoverflow.com">Stackoverflow Popup</a> be used where the popup: functio ...

How can I retrieve the top-level key based on a value within a JSON object nested in JavaScript?

If I have the value Africola for key name in the following nested JSON structure, how can I retrieve its corresponding upper-level key 'barID1' using JavaScript? { "barID1": { "address": "4 East Terrace, Sydney NSW 2000", "appStoreURL" ...

Tips for Navigating and Scrolling to an Element by its ID in a Next.js Page Enhanced with AnimatePresence

Currently, I am utilizing Framer Motion to add animations to the page transitions in a Next.js project. However, when implementing AnimatePresence, it seems to interfere with the navigation to specific elements using hash links (id). The seamless transitio ...

What is the role of the app.use method in ExpressJS in handling URL redirects that end with a "/"?

This script automatically redirects URLs that end with a "/" to the same URL without it. For example, if a user visits http://localhost:3000/about/, they will be directed to http://localhost:3000/about. This ensures that image URLs and other HTML file refe ...

What could be causing my controller to not capture the saved row?

Attempting to perform inline editing with jQgrid, I implemented the following: ...... colModel :[ ........ {name:'idProvino', index:'idProvino', editable: true}, ....... ...

Guide on integrating React.js into an HTML development webpage

I can't seem to get this code to work properly. I have saved it as an .html file on my computer, but it's not displaying anything when I try to open it in Google Chrome. <DOCTYPE! html> <html> <head> <script src= ...

Is it possible to fetch JSON data in PHP without having to encode it with json_encode()?

I've been trying my luck, but I'm curious if it's possible to retrieve JSON data if it's not encoded server-side with PHP. For instance, if I were to simply output some data like this: echo '{"subscriptions": [{"subscribe":"' ...

My form does not receive the Bootstrap classes when using the jQuery script

**Why isn't my jQuery script coloring the rows as expected when certain conditions are met (I italicized the specific part of the code)?** Here is the HTML CODE for the POLL: <form id="pollForm" class="mb-4"> <d ...

What is the best way to toggle a d3 svg overlay using a leaflet layer control?

I am looking for a solution to place 3 d3 svgs on a leaflet map and control them as easily as leaflet layers. Check out this code example, which works but is not ideal. The key part is from line 75 onwards, where I create a custom layer control linked to ...

Sending form data via Ajax for a specific field ID

When sending data to an ajax script, I usually create a form tag and assign it an id like this: <form id="myForm"> Then, in the ajax script, I include the following code: data: $('#myForm').serialize(), This sends all the form data. How ...

Is the setInterval function in JavaScript only active when the browser is not being used?

I am looking for a way to ensure proper logout when the browser is inactive using the setInterval() function. Currently, setInterval stops counting when the browser is active, but resumes counting when the browser is idle. Is there a way to make setInterv ...

Extracting address from a string containing HTML line breaks and apostrophes using JavaScript

I need help with parsing an address that is in a string format like the following: "1234 Something Street<br>Chicago, IL 34571<br>" I am struggling to extract and assign it to separate variables: var street = ...; var city = ...; var state = ...

What is the process for including the Authorization HTTP header in a JSONP request?

I am attempting to make a GET request to the Yelp API. When I use the code below, I encounter a 401 error. From my research, it seems that setting the authorization in this manner is not possible when requesting JSONP data. However, when I attempt another ...

AJAX request post parameters not recognized in ColdFusion form scope

I am currently developing a ColdFusion 8 training application that involves creating AJAX requests without using any libraries like jQuery. This is to support a basic CRUD application where data is retrieved and processed through various layers of the syst ...