Given the following code:
function move()
{
dom = document.getElementById('image');
dom.style.top=event.clientY+"px";
dom.style.left=event.clientX+"px";
}
<!DOCTYPE html>
<html>
<head>
<title>Program 3</title>
<script type="text/javascript" src="pr3.js"></script>
</head>
<body onmousedown="move();">
<img src="image.jpg" id="image" width="300px" height="200px" style="position:absolute; left:100px; top:100px;"/>
</body>
</html>
Edit
The image only moves when clicked on the image. But when clicked outside the image, it does not move.
However, without <!DOCTYPE html>
, it moves wherever clicked inside the browser window and not explicitly on the image.
Absolutely-positioned elements to not affect the size of their containing element. Consider a case where we use a red-colored
<div>
instead of<body>
as the clickable element:This snippet should contain a red-colored
<div>
, but it doesn't, because the<div>
is empty or anything that would cause it to have a size greater than 0. The image it contains is absolutely-positioned, which does not affect the size.Now consider a similar
<div>
with a CSS-specified size:Now the div is larger than zero, and clicking inside produces the expected result.
this is why your
<body>
clicks don't work: the<body>
has a width and height of 0. If you instead place theonclick
listener on the<html>
element (which is full-width and full-height by default) or on an element with non-zero dimensions, you'll see your code works. I'm not sure I'd advise putting binding click listeners on the<html>
element; I would advise using a CSS-sized<div>
.