<html>
<head>
<style>
#wrapper{
position: absolute;
top : 250px;
width: 500px;
height: 500px;
border: 1px solid red;
}
.tagging{
position: absolute;
border: 1px solid black;
width : 20px;
height: 30px;
}
</style>
<script>
window.onload = function(event){
var wrapper = document.getElementById("wrapper");
var wrapperOffsetTop = wrapper.offsetTop;
wrapper.onmousedown = function(event){
var div = document.createElement("div");
div.className = "tagging";
div.style.top = event.clientY - wrapperOffsetTop;
wrapper.appendChild(div);
}
}
</script>
</head>
<body>
<div id="wrapper">
</div>
</body>
</html>
I have developed a simple application where users can click on the area to append a box with the cursor position. However, it seems that the functionality is not working as expected.
After making some adjustments and adding +"px"
, the code worked perfectly for me.
But in my real-world application, the same approach does not seem to work as intended:
<html>
<head>
<style>
.tagging{
border: 1px solid red;
position: absolute;
padding: 0px;
margin: 0px;
width : 20px;
height: 20px;
}
</style>
<script>
window.onload = function(){
//get Information about imgWrapper
var imgWrapper = document.getElementById("imgwrapper");
var wrapperOffsetTop = imgWrapper.offsetTop;
var wrapperOffsetLeft = imgWrapper.offsetLeft;
//set the image wrapper to be the same size as the image
var img = document.getElementsByTagName('img');
imgWrapper.style.width = img[0].width;
//when image wrapper is clicked, append a div element
img[0].onmousedown = function(event) {
event.preventDefault();
//create tag with class
var div = document.createElement("div");
div.className = "tagging";
imgwrapper.appendChild(div);
//get the position of mouse cursor
var mouseX = event.clientX;
var mouseY = event.clientY;
//set the position of the div
div.style.top = (mouseY - wrapperOffsetTop) + "px";
div.style.left = (mouseX - wrapperOffsetLeft) + "px";
}};</script>;
</head>
<body>
<div id="imgwrapper">
<img src="jlin.jpg">
</div>
<form action="./yipee.php" method="POST" id="noob">
<input type="submit">
</form>
</body>
</html>