Move an Element with response to Click Position

by Sasikumar 2014-03-18 09:41:00

To move an element with response to click position use the following code,
<!DOCTYPE html>
<html>
<head>
<title>Move an Element with response to Click Position</title>
<style type="text/css">
body {
background-color: #0F0E0E;
margin: 30px;
margin-top: 10px;
}
#ground {
width: 90%;
height: 400px;
border: 5px #D1D1D1 solid;
overflow: hidden;
background-color:#000000;
cursor: url(fly.gif), auto;
margin-left: 60px;
}
#ball {
position: relative;
left: 50px;
top: 50px;
transition: left .5s ease-in, top .5s ease-in;
height:100px;
width:100px;
}
</style>
</head>
<body>
<div align="center">
<h4 style="color:#fff;">Move an Element with response to Click Position</h4>
</div>
<div id="ground">
<img id="ball" src="frog.png">
</div>
<script>
var theThing = document.querySelector("#ball");
var container = document.querySelector("#ground");

container.addEventListener("click", getClickPosition, false);

function getClickPosition(e) {
var parentPosition = getPosition(e.currentTarget);
var xPosition = e.clientX - parentPosition.x - (theThing.clientWidth / 2);
var yPosition = e.clientY - parentPosition.y - (theThing.clientHeight / 2);

theThing.style.left = xPosition + "px";
theThing.style.top = yPosition + "px";
}

function getPosition(element) {
var xPosition = 0;
var yPosition = 0;

while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
</script>
</body>
</html>

Images Used:
frog.png
fly.gif
543
like
0
dislike
0
mail
flag

You must LOGIN to add comments