zelusp zelusp - 2 months ago 6x
CSS Question

How to asynchronously move multiple overlayed images using javascript?

I have 10 shapes that collectively define a square image as shown below. I would like to move each image using the output of a periodic function like sine that takes user mouse position as an input. Each image should have a different frequency and period affecting it's motion so that as a user mouses over the scene the shapes jitter past each other.

enter image description here

So far I've managed to get 1 shape to move using this:

var track = function(ampl, freq) {
return {
x : ampl * Math.sin(freq*e.pageX),
y : ampl*1.6 * Math.sin(freq*e.pageY)

var current = track(10, 0.05);
$("#image").css({left:current.x, top:current.y});


How can I get this jsfiddle to do that for the other 9 shapes?


I would do something like this - http://jsfiddle.net/jfhk8bye/

track = function(ampl, freq, pageX, pageY) {
    return {
        x   : ampl * Math.sin(freq*pageX),
        y   : ampl*1.6 * Math.sin(freq*pageY)
$imgs = $('img.image')
    var $img = $(this);
    var current = track($img.data('ampl'), $img.data('freq'), e.pageX, e.pageY);
    $img.css({left:current.x, top:current.y});

What I did:

  • Qualified image IDs into classes instead (updating CSS too)
  • Added data attributes to the image elements representing their frequencies and amplitudes (this way you can control these values in HTML)
  • Updated your javascript appropriately and optimised it.