JavaScript Conga Line

Assuredly as some variables refused to be defined, there will come a day in every programmer’s career when he or she will be tasked with the creation of a conga line animation that follows the pointer around the screen. But said task need not cast a shadow over a developer’s brow as it can be quickly dispatched with just a few lines of JavaScript and jQuery.

$nodes.forEach(function(node, index) { 
$(document).on(‘mousemove’, function(e) {
setTimeout(function() {
node.css({
left: e.pageX,
top: e.pageY
});
}, 200 * index);
});
});

$nodes is the jQuery collection of HTML nodes itchin’ to partake in the Cuban carnival dance cum tropical-themed party novelty. Simply iterate over each node in the collection and add a mousemove event handler which positions the nodes right under the cursor (by setting their CSS left and top attributes to e.pageX and e.pageY respectively). The trick is to do this position-setting within a setTimeout that is offset for each node by a factor based on the iterating index over the collection: the 200 * index in the above example staggers each node by 200ms.

And if a picture is worth a thousand words, the mind can only reel at the value of a JSFiddle:

Everybody dance now.

A variation of this technique to remove tiles from a game board can be seen here:

BOOM
Minesweeper Simulation