Monday, May 27, 2013

Moving a div according to mouse coordinates using Javascript.

This post is similar to the post "Move a HTML Div with CSS and Javascript, No JQuery!" but in that post we are using user specified pixels by allowing user to add numbers of pixel in the text box. Here, in this post we are going to do the same thing but in a different way. We are going to use the coordinates of where our mouse clicks. Run the code in your browser you'll like it!

Before i start, let me say you, this question was asked by one reader who want to move his div according to mouse click. Well he's my uncle and he was taking my test :D.

Ok, let's get back to topic and implement javascript.
First of all before you start writing HTML don't forget to add doctype on the start or it will not support / it will not work. Because of doctype i'm adding full code from start to end below.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>Hey, this is for you!</title>
<style type="text/css">
#box {
<script type="text/JavaScript">
function moves(e){
var cordx = 0;
var cordy = 0;
if (!e) {
var e = window.event;
if (e.pageX || e.pageY){
cordx = e.pageX;
cordy = e.pageY;
else if (e.clientX || e.clientY){
cordx = e.clientX;
cordy = e.clientY;
document.getElementById('box').style.left = cordx;
document.getElementById('box') = cordy;
<body onClick="moves(event)">
<div id="box">Hey! this is for you, enjoy :)</div>

In the code we are using 'clientX' and 'clientY' to get the coordinates. We are also using 'pageX' and 'pageY'  to get he horizontal coordinate of the event relative to whole document.
To understand more or learn more about 'pageX', 'pageY', 'clientX', 'clientY' you can refer to the mozilla documentation.

I think so i have given the whole source code so it's no need to upload the file and share download link.


  1. Thank you so much. I really wanted to learn this, and not the jquery version. This gives me a better understanding of how things happen and not just magic.

  2. Thank You very much this is a great script. I was wondering if you could tell me how you would do the same thing if you had multiple div elements with different ID's and different onclick events. Such as you would have with locations on a map and are using the onclick to also show a dialog box for each separate location?


Your Comment Will Be Visible After Approval, Thanks !