JSFiddle - React, Tailwind, and code Playground
by Manuellama
HTML
<html>
<body>
<form name="Show">
X <input type="text" name="MouseX" value="0" size="4"><br>
Y <input type="text" name="MouseY" value="0" size="4"><br>
</form>
<div class="item" draggable="true" style="background:#990033;left:440px;top:0px;width:200px;height:200px;z-index:auto; position:absolute;">
You can drag and drop this block on text on any part of the screen. It will stay on the screen, even if you try to drop it outside it.(800 x 600 region)
</div>
</body>
</html>
CSS
.item {
color:#FFFFFF;
font-family:Arial, Helvetica, sans-serif;
font-size:small;
width:200px;
height:200px;
left:auto;
top:auto;
}
JavaScript
var mx=0;
var my=0;
var mouse;
var tempX = 0;
var tempY = 0;
var fire = 0;
var IE = document.all?true:false;
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
function handleDragStart(e) {
getMousePos(this,e)
e.dataTransfer.setData('text/html', this.id);
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
}
function handleDragEnd(e) {
alert(mouse.mousex);
var cols = document.querySelectorAll('.item');
[].forEach.call(cols, function(col) {
col.style.zIndex =0;
});
this.style.zIndex = 1;
var h = String(this.style.height);
h = h.replace("px","");
mouse.mousex = tempX;
mouse.mousey = tempY;
if (mouse.mousex>800){
mouse.mousex = 800;
}
if (mouse.mousey>600-Number(h)){
mouse.mousey= 600-Number(h);
}
this.style.left = mouse.mousex+"px";
this.style.top = mouse.mousey+"px";
}
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft-mx;
tempY = event.clientY + document.body.scrollTop-my;
}
else { // grab the x-y pos.s if browser is NS
tempX = e.pageX-mx;
tempY = e.pageY-my;
}
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
document.Show.MouseX.value = tempX;
document.Show.MouseY.value = tempY;
mouse = {mousex:tempX,mousey:tempY};
}
function getMousePos(canvas, evt){
// get canvas position
var obj = canvas;
var top = 0;
var left = 0;
while (obj.tagName != 'BODY') {
top += obj.offsetTop;
left += obj.offsetLeft;
obj = obj.offsetParent;
}
// return relative mouse position
var mouseX = evt.clientX - left + window.pageXOffset;
var mouseY = evt.clientY - top + window.pageYOffset;
mx =...