Move Elements on Mouse Click Using jQuery

Introduction

Hi, how are you today? Today we will see how to move an element when the user clicks the mouse. The element is moved to the position the mouse is clicked. This is a simple demo for that. I hope you will enjoy it.

Using the code

To work with this demo, we need to load the jQuery file first.
[js]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
[/js]

Need some elements, right?
[html]
<b>Where ever you go, I am there</b>
<p id="go">
<img src="http://sibeeshpassion.com/Content/Images/sibi.jpg" alt="www.sibeeshpassion.com" />
</p>
[/html]

We are loading an image to a p tag.

Now we will style those elements.
[css]
#go {
position: absolute;
background-color: blue;
color: #fff;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
width: 100px;
}
[/css]

So shall we go and write the jQuery code now?
[js]
$(document).ready(function () {
var XPosition = 0;
var YPosition = 0;
var $go = $("#go");
$(document).click(function (e) {
XPosition = e.pageX;
YPosition = e.pageY;
$go.stop().animate({ top: YPosition, left: XPosition });
});
});
[/js]

We are taking the element “go” into a script variable, then we will get the click positions first whenever the user clicks anywhere in the window.
[js]
var $go = $("#go");
XPosition = e.pageX;
YPosition = e.pageY;
[/js]

Now we will assign these positions to the element “go”.
[js]
$go.stop().animate({ top: YPosition, left: XPosition });
[/js]

Complete Code
[html]
<!DOCTYPE html>
<html>
<head>
<title>Move elements on click demo – Sibeesh Passion</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
#go {
position: absolute;
background-color: blue;
color: #fff;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
width: 100px;
}
</style>
<script>
$(document).ready(function () {
var XPosition = 0;
var YPosition = 0;
var $go = $("#go");
$(document).click(function (e) {
XPosition = e.pageX;
YPosition = e.pageY;
$go.stop().animate({ top: YPosition, left: XPosition });
});
});
</script>
</head>
<body>
<b>Where ever you go, I am there</b>
<p id="go">
<img src="http://sibeeshpassion.com/Content/Images/sibi.jpg" alt="www.sibeeshpassion.com" />
</p>
</body>
</html>
[/html]

That is all, so shall we see the output now?
Output

Output
Conclusion

I hope you liked this article, please share me your suggestions. Thanks in advance.

Kindest Regards,
Sibeesh Venu

Leave a Reply

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

Serverless 360