Back to all resources
mouse events
dynamic styling
grid layout
swarm

Interactive Squares

By Jared Malan
This JavaScript code creates a dynamic grid of elements that react to mouse movement by simulating a swarm-like behavior. The grid is composed of individual 'div' elements styled as squares, which are appended to the body of the document. Each square can independently move in response to the mouse cursor's proximity.

Key Components:

  • Constants and Variables: swarmSize, rows, cols, and swarms define the size of each grid element, the number of rows and columns in the grid, and an array to store each element, respectively.
  • createSwarmGrid Function: This function initializes the grid. It calculates the grid's dimensions and positions it centrally on the screen. Each grid element is created, positioned based on its row and column, and stored in the swarms array.
  • handleMouseMove Function: Attached to the mousemove event of the body, this function adjusts the position and rotation of each grid element based on its distance from the mouse cursor. Elements move away from the cursor if they are within a certain range, and return to their original position when the cursor moves away.
  • CSS Styling: Basic styles are applied to ensure the grid elements are positioned absolutely and have transitions for smooth movement.

The code also includes an event listener for mouse movements and invokes the createSwarmGrid function to set up the grid when the script runs.