I have a bunch of span elements in random positions enclosed inside a parent div called ‘.background’. These are generated with Javascript. Like this:
<span class="circle" style="width: 54px; height: 54px; background: #5061cf; top: 206px; left: 306px"></span>
I want them to move away (or repel) as the mouse draws near, but I have no idea how to do this! How would I go about accomplishing this in jQuery?
I imagine you’d have to search for spans that were nearby, and then change their position if they were inside a certain radius surrounding the mouse, but I really don’t know where to start. Any help is appreciated!
A simple approach would be to wrap each span in another, larger span. Make it larger on each side by the minimal distance you want the mouse to be able to approach the inner spans. Bind a function (
evade) that moves each wrapper tomouseoveron the wrappers. This approach gives you a square border, so if the graphical elements in the inner spans aren’t square, the distance from the mouse to the graphical element’s border won’t be constant, but is easy to implement.Alternatively, use the bumper for a rough proximity test. Instead of binding the evade function to
mouseover, bind a function (beginEvade) that bindsevadeon mousemove. Also, bind a function tomouseoutthat unbindsevade. Yourevadecan then perform a more precise proximity test.First, find a good geometry library that provides a vector type. In absence of one, here’s a sample implementation:
Next, a sample circular evasion function (which is the simplest to implement). Outline:
In code:
After that, all that’s left are functions to bind/unbind
evade, and the calls to set everything up.You can preview this in jsFiddle