I want to show the coordinates of the mouse until the cursor is over the red div and the mouse button is there.
The problem is that I unlock the button outside the div and put the cursor back into the div, the onmousemove event is not deleted.
NOTE. I do not want to use any library like jQuery.
<script type="text/javascript">
window.onload = function(){
document.getElementById("thediv").onmousedown = AttachEvent;
}
function GetPos(e){
document.getElementById('X').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
document.getElementById('Y').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
function UnaatachEvent(e){
document.getElementById("thediv").onmousemove = null;
document.getElementById("thediv").onmouseup = null;
}
function AttachEvent(e){
document.getElementById("thediv").onmousemove = GetPos;
document.getElementById("thediv").onmouseup = UnaatachEvent;
}
</script>
</head>
<body>
<input type="text" id="X" size="3">X-position
<br/>
<br/>
<input type="text" id="Y" size="3">Y-position
<div style="width:100px;height:100px;background-color:red;margin:auto;" id="thediv">
</div>
</body>
UPDATE:
With jQuery it is very simple: (tested only in Firefox)
link text
$(document).ready(function(){
$('#thediv').mousedown(attachEvent);
});
function attachEvent(e){
$('#thediv').mousemove(getPos).mouseup(unattachEvent);
return false;
}
function getPos(e){
document.getElementById('X').value = e.pageX;
document.getElementById('Y').value = e.pageY;
return false;
}
function unattachEvent(e){
$('#thediv').unbind("mousemove", getPos).unbind("mouseup", unattachEvent);
Pay attention to the main scenarios:
- If the button was pressed outside the square, and while holding it, moved to suqre - do not update the position.
- If the button was pressed inside the square, and while holding, go to the street - stop updating, return it (without releasing the button) continue updating
, mousedown .
javascript.