Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to animate an image to move away from cursor postion on each mouseover?

I'm trying to animate an image of a box by changing it's position on mouseover.

I can get it to move once but I need to set it up so that it moves everytime someone mouses over the image. I want to make the users 'chase' the box around the screen.

Preferably the animation would loop so that a user can never catch the image ?

Here is an example of what I have so far, and below is my jQuery code:

$(document).ready(function() {
    $('#img').mouseover(function() {
        $(this).animate({
            left: '500px'
        });
    });
});

Thanks a million!

like image 586
Aoife O'Dwyer Avatar asked Dec 08 '11 21:12

Aoife O'Dwyer


1 Answers

Here is an example. It covers basics I guess.

jQuery(function($) {
    $('#img').mouseover(function() {
        var dWidth = $(document).width() - 100, // 100 = image width
            dHeight = $(document).height() - 100, // 100 = image height
            nextX = Math.floor(Math.random() * dWidth),
            nextY = Math.floor(Math.random() * dHeight);
        $(this).animate({ left: nextX + 'px', top: nextY + 'px' });
    });
});
like image 172
Emre Erkan Avatar answered Sep 28 '22 17:09

Emre Erkan