Move object toward mouse click position using jQuery

In this tutorial I am going to show you how to move object toward mouse click position using jQuery. Before going to details of the source code let’s have a look at the LIVE demo.

STEP: 1 (Move object toward mouse click position)

At first, Add the jQuery library in the head section of your HTML webpage.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

Now, please write down the jQuery code written below in your .js file or in the head section of your HTML webpage.

$(document).click(function(event) {
    var x = event.pageX,
    y = event.pageY;
                  
    $('#banana').animate({
        top: y - 36,
        left: x - 36
    }, 500);
});

On the code above we have used animate() function on line 5 to move object toward mouse click position. The size of the image we have used here is 64×64. So in order to move the centre of the object to the mouse click position we used top: y – 36; and left: x – 36; on line 6 and 7 respectively. The way of calculating the value is y – (height_of_the_object/2 + (height_of_the_object/2)/8). Here the height of our image is 64. That is why we moved our object to top: y – (64/2 + (64/2)/8); which is y – 36. Same calculation goes for x too. But when we calculate the x value we will take the width of our image instead of height. The value 500 on line 8 is the animation time.

STEP: 2 (Move object toward mouse click position)

Now write down the CSS code in the head section of your HTML webpage.

#banana {
    padding: 5px;
    position : absolute; 
    top: 50px;
    left: 50px;
}

STEP: 3 (Move object toward mouse click position)

Finally, write down the following HTML code in the body section of your HTML webpage.

<p>Click anywhere on the screen to move the dancing banana</p>
<img src="http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif" width="64" height="64" id="banana"/>

If you have any questions feel free to ask me in the comment section. Hope you enjoy this post!

Leave a Reply

Your email address will not be published. Required fields are marked *

four × 2 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.