Javascript Prevent Draggable div outside parent div - javascript

I have draggable div. I want this draggable div to be restricted within parent using javascript. I know how to prevent draggable div using jquery UI draggable plugin. But I am not sure how to restrict draggable using native javascript. Please find below my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.draggabletarget {
float: left;
width: 100px;
height: 35px;
margin: 15px;
padding: 10px;
border: 1px solid #aaaaaa;
}
</style>
</head>
<body>
<div class="parent" style="border:1px solid red;height:600px;width:600px;">
<div class="draggabletarget" ondragstart="dragStart(event)" ondrag="dragging(event)" draggable="true" id="dragtarget">
<p >Drag me!</p>
</div>
</div>
<script>
function dragStart(event) {
event.dataTransfer.setData("Text", event.target.id);
}
function dragging(event) {
document.getElementById("demo").innerHTML = "The p element is being dragged";
}
function allowDrop(event) {
event.preventDefault();
}
</script>
</body>
</html>
In this code i have a div with class parent. I want my draggable div whose class is draggabletarget shouldn't drag outside the parent div. How can i do this in native javascript. Please suggest

function $(el){
return document.getElementById(el);
}
var isDragging = false;
var tzdragg = function(){
return {
move : function(divid,xpos,ypos){
var a = $(divid);
$(divid).style.left = xpos + 'px';
$(divid).style.top = ypos + 'px';
},
setDragging : function() {
isDragging = true;
},
resetDragging : function() {
isDragging = false;
},
startMoving : function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
a = $('elem'),
divTop = a.style.top,
divLeft = a.style.left;
divTop = divTop.replace('px','');
divLeft = divLeft.replace('px','');
var diffX = posX - divLeft,
diffY = posY - divTop;
document.onmousemove = function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
aX = posX - diffX,
aY = posY - diffY;
var boun=document.getElementById("parent").offsetWidth-document.getElementById("elem").offsetWidth;
if((aX>0)&&(aX<boun)&&(aY>0)&&(aY<boun))
tzdragg.move('elem',aX,aY);
}
},
stopMoving : function(){
var a = document.createElement('script');
document.onmousemove = function(){}
if(!isDragging) {
console.log('clicked');
}
},
}
}();
#elem
{
position: absolute;
width: 100px;
height: 100px;
background-color: black;
-webkit-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
-khtml-user-select: none;
user-select: none;
cursor: default;
}
<div style="height:400px; width:400px; border:solid 1px black;position: absolute;top: 0;
left: 0;" id='parent'>
<div id='elem' onmousedown='tzdragg.resetDragging();tzdragg.startMoving(event);' onmouseup='tzdragg.stopMoving();' onmousemove='tzdragg.setDragging();'
>
</div>
</div>

If you need to use pure javascript.
<div id='container'>Drag the box around</div>
<div id='slider'></div>
body {
background-color : lightgray;
}
#container {
position : fixed;
border-radius : 10px;
background-color : brown;
border : solid 1px black;
font : 15px arial,sans-serif;
text-align : center;
}
#slider {
position : fixed;
border-radius : 10px;
background: black;
}
div {
cursor : default;
}
document.onselectstart = function(e) {
e.preventDefault();
return false;
}
var slider = document.getElementById('slider'),container = document.getElementById('container');
document.mouseState = 'up';
slider.mouseState = 'up';
slider.lastMousePosY = null;
slider.lastMousePosX = null;
slider.proposedNewPosY = parseInt(slider.style.top, 10); //converts '10px' to 10
slider.proposedNewPosX = parseInt(slider.style.left, 10);
slider.style.top = '40px';
slider.style.left = '40px';
slider.style.height = '60px';
slider.style.width = '60px';
container.style.top = '20px';
container.style.left = '20px';
container.style.height = '200px';
container.style.width = '400px';
document.onmousedown = function() {
document.mouseState = 'down';
};
document.onmouseup = function() {
document.mouseState = 'up';
slider.mouseState = 'up';
};
slider.onmousedown = function(e) {
slider.lastMousePosY = e.pageY;
slider.lastMousePosX = e.pageX;
slider.mouseState = 'down';
document.mouseState = 'down';
};
slider.onmouseup = function(e) {
slider.mouseState = 'up';
document.mouseState = 'up';
};
var getAtInt = function getAtInt(obj, attrib) {
return parseInt(obj.style[attrib], 10);
};
document.onmousemove = function(e) {
if ((document.mouseState === 'down') && (slider.mouseState === 'down')) {
slider.proposedNewPosY = getAtInt(slider, 'top') + e.pageY - slider.lastMousePosY;
slider.proposedNewPosX = getAtInt(slider, 'left') + e.pageX - slider.lastMousePosX;
if (slider.proposedNewPosY < getAtInt(container, 'top')) {
slider.style.top = container.style.top;
} else if (slider.proposedNewPosY > getAtInt(container, 'top') + getAtInt(container, 'height') - getAtInt(slider, 'height')) {
slider.style.top = getAtInt(container, 'top') + getAtInt(container, 'height') - getAtInt(slider, 'height') + 'px';
} else {
slider.style.top = slider.proposedNewPosY + 'px';
}
if (slider.proposedNewPosX < getAtInt(container, 'left')) {
slider.style.left = container.style.left;
} else if (slider.proposedNewPosX > getAtInt(container, 'left') + getAtInt(container, 'width') - getAtInt(slider, 'width')) {
slider.style.left = getAtInt(container, 'left') + getAtInt(container, 'width') - getAtInt(slider, 'width') + 'px';
} else {
slider.style.left = slider.proposedNewPosX + 'px';
}
slider.lastMousePosY = e.pageY;
slider.lastMousePosX = e.pageX;
}
};
here is working example

Related

How to make a draggable div resize-able on all 4 corners with pure javascript?

I noticed these resize pointers in the css spec...
https://drafts.csswg.org/css-ui-3/#valdef-cursor-se-resize
Is there a CSS shortcut for 4 corner resizability similar to the one corner ('resize: both') method?
If not, are there known conflicts when combining resizability with a draggable div?
My starting point was here...
https://www.w3schools.com/howto/howto_js_draggable.asp
Any help navigating the posX, posY is appreciated.
notes for getBoundingClient()
———---
| |
|____ | div.getBoundingClientRect()
SE (bottom right):
Height and width / top and left are stationary
SW (bottom left):
Height and width and left / top is stationary
NW (top left):
Height and width top and left
NE (top right):
Height and width and Top / Left is stationary
edit: removed padding and borders.
const myDiv = document.getElementById('mydiv')
let isResizing = false;
//Make the DIV element draggable:
dragElement(myDiv);
function dragElement(elmnt) {
if (!isResizing) {
let pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
//if present, the header is where you move the DIV from:
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
//otherwise, move the DIV from anywhere inside the DIV:
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
//stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}
}
// Resize
(function fourCorners() {
const resizers = document.querySelectorAll('.resizer')
let currentResizer
for (let resizer of resizers) {
resizer.addEventListener('mousedown', mouseDown)
function mouseDown(e) {
currentResizer = e.target
e.preventDefault()
isResizing = true;
let posX = e.clientX;
let posY = e.clientY;
myDiv.addEventListener('mousemove', mouseMove)
myDiv.addEventListener('mouseup', mouseUp)
function mouseMove(e) {
e.preventDefault()
const rect = myDiv.getBoundingClientRect()
if (currentResizer.classList.contains('se')) {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width - (posX - e.clientX) + 'px';
myDiv.style.height = rect.height - (posY - e.clientY) + 'px';
} else if (currentResizer.classList.contains('sw')) {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width + (posX - e.clientX) + 'px';
myDiv.style.height = rect.height - (posY - e.clientY) + 'px';
myDiv.style.left = rect.left - (posX - e.clientX) + 'px';
} else if (currentResizer.classList.contains('ne')) {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width - (posX - e.clientX) + 'px';
myDiv.style.height = rect.height + (posY - e.clientY) + 'px';
myDiv.style.top = rect.top - (posY - e.clientY) + 'px';
} else {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width + (posX - e.clientX) + 'px';
myDiv.style.height = rect.height + (posY - e.clientY) + 'px';
myDiv.style.top = rect.top - (posY - e.clientY) + 'px';
myDiv.style.left = rect.left - (posX - e.clientX) + 'px';
}
posX = e.clientX;
posY = e.clientY;
}
function mouseUp(e) {
myDiv.removeEventListener('mousemove', mouseMove)
myDiv.removeEventListener('mouseup', mouseUp)
isResizing = false
}
}
}
})()
* {
margin: 0;
padding : 0;
}
#mydiv {
position: absolute; /* NECESSARY */
background-color: whitesmoke;
box-sizing: border-box;
text-align: center;
/* border: 1px solid #222; */
height: 200px;
width: 200px;
/* resize: both; /* CSS RESIZE */
overflow: hidden; /* CSS RESIZE */
}
#mydivheader {
/* padding: 10px; */
cursor: move;
background-color: dodgerblue;
color: #fff;
}
#content {
color: #000;
margin: 0px;
background-color: whitesmoke;
}
/* ::-webkit-resizer {
position: absolute;
height: 20px;
width: 20px;
border-top-left-radius: 25px;
background-color: #dd0;
z-index: 2;
} */
.resizer {
position: absolute;
height: 20px;
width: 20px;
background-color: #dd0;
z-index: 2;
}
.resizer.nw {
top: -1px;
left: -1px;
cursor: nw-resize;
border-bottom-right-radius: 25px;
}
.resizer.ne {
top: -1px;
right: -1px;
cursor: ne-resize;
border-bottom-left-radius: 25px;
}
.resizer.sw {
bottom: -1px;
left: -1px;
cursor: sw-resize;
border-top-right-radius: 25px;
}
.resizer.se {
bottom: -1px;
right: -1px;
cursor: se-resize;
border-top-left-radius: 25px;
}
<div id="mydiv">
<div class='resizer nw'></div>
<div class='resizer ne'></div>
<div class='resizer sw'></div>
<div class='resizer se'></div>
<div id="mydivheader">Click here to move
<div id='content'>
<div id='image-container'><img height='auto' width='100%' src='https://picsum.photos/600' /></div>
</div>
</div>
</div>
Well if you want to make it nice and easy you could use jQuery to help it resize would probably be the easiest way. Then after you learn how to do it with jQuery you could do it with pure js.
So, you want the resize handle to appear on all four corners? That'll require some bounds checking.
You can modify the offset check in drag to account for any corner and handle the drag as a resize event instead. The code somewhat works for top-left and bottom-right resizing, but doe not work too well with the opposite corners. This is a start.
This is a start:
const cursor = document.querySelector('#cursor');
const cornerThreshold = 4;
const dragStart = e => {
const [ horz, vert ] = getDirection(e, cornerThreshold);
const bounds = e.target.getBoundingClientRect();
const cursor = getCursorType(e);
if (cursor === 'grab') {
e.target.dataset.isDragging = true;
} else {
e.target.dataset.isResizing = true;
}
e.target.dataset.startWidth = bounds.width;
e.target.dataset.startHeight = bounds.height;
e.target.dataset.originX = e.clientX;
e.target.dataset.originY = e.clientY;
e.target.dataset.offsetX = e.clientX - e.target.offsetLeft;
e.target.dataset.offsetY = e.clientY - e.target.offsetTop;
e.target.dataset.dirHorz = horz;
e.target.dataset.dirVert = vert;
e.target.style.zIndex = 999;
};
const dragEnd = e => {
delete e.target.dataset.isDragging;
delete e.target.dataset.offsetX;
delete e.target.dataset.offsetY;
delete e.target.dataset.originX;
delete e.target.dataset.originY;
delete e.target.dataset.startWidth;
delete e.target.dataset.startHeight;
delete e.target.dataset.dirHorz;
delete e.target.dataset.dirVert;
delete e.target.dataset.resizeDirection;
e.target.style.removeProperty('z-index');
e.target.style.removeProperty('cursor');
};
const drag = e => {
e.target.style.cursor = getCursorType(e);
cursor.textContent = `(${e.clientX}, ${e.clientY})`;
if (e.target.dataset.isDragging) {
e.target.style.left = `${e.clientX - parseInt(e.target.dataset.offsetX, 10)}px`;
e.target.style.top = `${e.clientY - parseInt(e.target.dataset.offsetY, 10)}px`;
} else if (e.target.dataset.isResizing) {
const bounds = e.target.getBoundingClientRect();
const startWidth = parseInt(e.target.dataset.startWidth, 10);
const startHeight = parseInt(e.target.dataset.startWidth, 10);
const deltaX = e.clientX - parseInt(e.target.dataset.originX, 10);
const deltaY = e.clientY - parseInt(e.target.dataset.originY, 10);
const originX = parseInt(e.target.dataset.originX, 10);
const originY = parseInt(e.target.dataset.originY, 10);
const dirHorz = parseInt(e.target.dataset.dirHorz, 10);
const dirVert = parseInt(e.target.dataset.dirVert, 10);
if (dirHorz < 0) {
e.target.style.left = `${originX + deltaX}px`;
e.target.style.width = `${startWidth - deltaX}px`
} else if (dirHorz > 0) {
e.target.style.width = `${startWidth + deltaX}px`;
}
if (dirVert < 0) {
e.target.style.top = `${originY + deltaY}px`;
e.target.style.height = `${startHeight - deltaY}px`;
} else if (dirVert > 0) {
e.target.style.height = `${startHeight + deltaY}px`;
}
}
};
const focus = e => { };
const unfocus = e => { e.target.style.removeProperty('cursor'); };
const getDirection = (e, threshold) => {
const bounds = e.target.getBoundingClientRect();
const offsetX = e.clientX - e.target.offsetLeft;
const offsetY = e.clientY - e.target.offsetTop;
const isTop = offsetY <= threshold;
const isLeft = offsetX <= threshold;
const isBottom = offsetY > (bounds.height - threshold);
const isRight = offsetX > (bounds.width - threshold);
if (isTop && isLeft) return [ -1, -1 ];
else if (isTop && isRight) return [ -1, 1 ];
else if (isBottom && isLeft) return [ 1, -1 ];
else if (isBottom && isRight) return [ 1, 1 ];
else return [ 0, 0 ];
};
const getCursorType = (e) => {
if (e.target.dataset.isDragging) {
return 'grabbing';
} else {
const [ horz, vert ] = getDirection(e, cornerThreshold);
const isTop = vert === -1;
const isLeft = horz === -1;
const isBottom = vert === 1;
const isRight = horz === 1;
if ((isTop && isLeft) || (isBottom && isRight)) return 'nwse-resize';
if ((isTop && isRight) || (isBottom && isLeft)) return 'nesw-resize';
}
return 'grab';
};
document.querySelectorAll('.draggable').forEach(draggable => {
draggable.addEventListener('mousedown', dragStart);
draggable.addEventListener('mouseup', dragEnd);
draggable.addEventListener('mousemove', drag);
draggable.addEventListener('mouseenter', focus);
draggable.addEventListener('mouseleave', unfocus);
});
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.container {
position: relative;
width: 60%;
height: 60%;
border: thin solid grey;
}
.square {
position: absolute;
height: 2em;
width: 2em;
}
.color-red { background: red; }
.color-blue { background: blue; }
.color-green { background: green; }
#square-1 { top: 10px; left: 10px; }
#square-2 { top: 50px; left: 50px; }
#square-3 { top: 100px; left: 100px; }
<div class="container">
<div id="square-1" class="square color-red draggable resizable"></div>
<div id="square-2" class="square color-blue draggable resizable"></div>
<div id="square-3" class="square color-green draggable resizable"></div>
</div>
<br />
<div>Cursor: <span id="cursor">(0, 0)</span></div>

Javascript move all childs inside div element

I'm trying to create a simple drag function that moves all childs inside a div tag depending on mouse movement, in simple world I calculate deltaX and deltaY and apply those to all childs inside a div by changing style.top and style.left. As regarding the X coordinate it works well while Y doesn't work (only increase) and I cannt explain why. This is what I have done
//Make the DIV element draggagle:
dragElement(document.getElementById(("mydiv")));
function dragElement(elmnt) {
var deltaX = 0, deltaY = 0, initX = 0, initY = 0;
var flag=true;
elmnt.onmousedown = dragMouseDown;
var childrens;
function dragMouseDown(e) {
e = e || window.event;
//console.log("dragMouseDown: "+e.clientX+" "+e.clientY);
childrens = document.getElementById("mydiv").querySelectorAll(".child");
// get the mouse cursor position at startup:
initX = e.clientX;
initY = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
if(flag){
flag=false;
e = e || window.event;
// calculate the new cursor position:
deltaX = e.clientX-initX;
deltaY = e.clientY-initY;
console.log("deltaX: "+deltaX+" deltaY: "+deltaY);
for (var i = 0; i < childrens.length; i++) {
//console.log("childrens[i].offsetTop: "+childrens[i].offsetTop+" childrens[i].offsetLeft: "+childrens[i].offsetLeft);
childrens[i].style.top = (childrens[i].offsetTop + deltaY) + "px"; // dont work (only increase)
childrens[i].style.left = (childrens[i].offsetLeft + deltaX) + "px";
}
initX = e.clientX;
initY = e.clientY;
deltaX=0;
deltaY=0;
flag=true;
}
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}
#mydiv {
position: fixed;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
width:400px;
height:400px;
border: 1px solid #d3d3d3;
}
.child {
position: relative;
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Draggable DIV Element</h1>
<p>Click and hold the mouse button down while moving the DIV element</p>
<div id="mydiv" style="background-color:blue">
<p class="child" style="background-color:red">Move 1</p>
</div>
Try something like this:
dragElement(document.getElementById(("mydiv")));
function dragElement(elmnt) {
var deltaX = 0,
deltaY = 0,
initX = 0,
initY = 0;
var flag = true;
elmnt.onmousedown = dragMouseDown;
var childrens;
function dragMouseDown(e) {
e = e || window.event;
childrens = document.getElementById("mydiv").querySelectorAll(".child");
for (var i = 0; i < childrens.length; i++) {
childrens[i].style.top = childrens[i].style.top == "" ? "0px" : childrens[i].style.top;
childrens[i].style.left = childrens[i].style.left == "" ? "0px" : childrens[i].style.left;
}
initX = e.clientX;
initY = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
if (flag) {
flag = false;
e = e || window.event;
deltaX = e.clientX - initX;
deltaY = e.clientY - initY;
for (var i = 0; i < childrens.length; i++) {
childrens[i].style.top = parseInt(childrens[i].style.top) + deltaY + "px";
childrens[i].style.left = parseInt(childrens[i].style.left) + deltaX + "px";
}
initX = e.clientX;
initY = e.clientY;
flag = true;
}
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
}
}
#mydiv {
position: fixed;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
width: 400px;
height: 400px;
border: 1px solid #d3d3d3;
}
.child {
position: relative;
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
<h1>Draggable DIV Element</h1>
<p>Click and hold the mouse button down while moving the DIV element</p>
<div id="mydiv" style="background-color:blue">
<p class="child" style="background-color:red">Move 1</p>
<p class="child" style="background-color:yellow">Move 2</p>
</div>
This isn't a nice solution but it works. Consider using jQuery and jQuery Draggable.

Create and position divs relative to parent

I am trying to create(and position) rectangle divs on a parent div. The created div should be positioned relative. Here is a working jsfiddle example -> Just draw some rectangles by holding mouse button.
var newRect = null;
var offset = $('#page').offset();
function point(x, y) {
this.x = x;
this.y = y;
}
function rect(firstPoint) {
this.firstPoint = firstPoint;
this.div = document.createElement("div");
this.div.style.position = "relative";
this.div.style.border = "solid 1px grey";
this.div.style.top = this.firstPoint.y+"px";
this.div.style.left = this.firstPoint.x+"px";
this.div.style.width = "0px";
this.div.style.height = "0px";
$("#page").append(this.div);
}
$("#page").mousedown(function (e) {
if(e.which == 1) {
var x = e.pageX - offset.left;
var y = e.pageY - offset.top;
newRect = new rect(new point(x, y));
}
});
$("#page").mousemove(function (e) {
if(newRect) {
newRect.div.style.width = Math.abs(newRect.firstPoint.x-(e.pageX - offset.left))+"px";
newRect.div.style.height = Math.abs(newRect.firstPoint.y-(e.pageY - offset.top))+"px";
}
});
$("#page").mouseup(function (e) {
if(e.which == 1 && newRect != null) {
if(Math.abs(newRect.firstPoint.x-(e.pageX - offset.left)) < 10) {
$("#"+newRect.div.id).remove();
newRect = null;
return;
}
$("#"+newRect.div.id).on('mousedown', function (e) {
e.stopImmediatePropagation();
});
newRect = null;
}
});
#page{
width: 210mm;
height: 297mm;
border:solid 2px #6D6D6D;
cursor: crosshair;
background-color: white;
float:left;
background-repeat: no-repeat;
background-size: contain;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page">
</div>
After drawing the first rectangle, which is positioned correctly, each rectangle is positioned false. I think that there is something wrong with the calculation of the position... maybe someone can give me a hint.
Change
this.div.style.position = "relative";
to
this.div.style.position = "absolute";
Bonus: Here's a version that allows you to draw in any direction: https://jsfiddle.net/g4z7sf5c/5/
I simply added this code to the mousemove function:
if (e.pageX < newRect.firstPoint.x) {
newRect.div.style.left = e.pageX + "px";
}
if (e.pageY < newRect.firstPoint.y) {
newRect.div.style.top = e.pageY + "px";
}

When I want to make a draggable div I couldn't avoid selecting neighboured text

I am a JS beginner.
I have made a draggable <div>. When I drag it, it will select one or two words near the <div> or glint with the blue select box (see the code-snippet below).
It bothers the experience feeling a little. What I want most is to keep other normal words being selected when dragging dhe <div>.
Please help me optimize the code or tell me if there is any syntax mistake.
window.onload = function() {
var parent = document.getElementById('parent');
eventFunc.addEventListener(parent, 'mousedown', dragItem);
}
function dragItem(ev) {
ev = ev || window.event;
var element = eventFunc.target(ev);
var spaceX = ev.clientX - element.offsetLeft,
spaceY = ev.clientY - element.offsetTop,
maxX = (document.documentElement.clientWidth || document.body.clientWidth) - element.offsetWidth,
maxY = (document.documentElement.clientHeight || document.body.clientHeight) - element.offsetHeight;
document.onmousemove = function(ev) {
ev = ev || window.event;
eventFunc.stopPropagation(ev);
element.style.left = (ev.clientX - spaceX) + 'px';
element.style.top = (ev.clientY - spaceY) + 'px';
if (element.offsetLeft < 0) {
element.style.left = 0;
} else if (element.offsetLeft > maxX) {
element.style.left = maxX + 'px'
}
if (element.offsetTop < 0) {
element.style.top = 0;
} else if (element.offsetTop > maxY) {
element.style.top = maxY + 'px'
}
}
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
}
var eventFunc = {
addEventListener: function(element, type, func) {
if (addEventListener) {
element.addEventListener(type, func, false);
} else if (attachEvent) {
element.attachEvent('on' + type, func);
} else {
element['on' + type] = func;
}
},
target: function(ev) {
return ev.target || ev.srcElement;
},
stopPropagation: function(ev) {
if (ev.stopPropagation) {
ev.stopPropagation();
} else {
ev.cancelBubble = true;
}
},
preventDefault: function(ev) {
if (ev.preventDefault) {
ev.preventDefault();
} else {
ev.returnValue = false;
}
}
}
#parent {
width: 400px;
height: 300px;
position: absolute;
border: 3px solid #ccc;
top: 0;
left: 0;
cursor: all-scroll;
text-align: center;
font: bold 35px/35px'Segoe UI', arial, helvetica, sans-serif;
color: #ccc;
}
#children {
text-align: left;
color: initial;
font: initial;
cursor: auto;
margin: 1em;
border: 1px solid red;
}
Outside Words
<div id="parent">
<div id="children">I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element.</div>
DRAG ME
</div>
</body>
inside your dragItem function.... add the following line...
function dragItem(ev) {
ev.preventDefault()
}
[edit (fulfilling the rest of the question)]
To select contents of any piece of content... you can use this function...
function selectNode(el) {
var range = document.createRange()
range.selectNodeContents(el)
var sel = window.getSelection()
sel.removeAllRanges()
sel.addRange(range)
}
// use it by passing in a node
selectNode(document.getElementById('parent'))

Error in javascript Drag and Drop

I have done drag and drop of popup in JavaScript and it is dragged in all directions properly but down.MouseUp event is not triggered properly when I drag the popup towards down.So that it is moving even though I released mouse. I am really screwed up with this bug.Please help..I have to resolve it urgently....
Here is my code..
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<style>
body{
margin:0px;
padding:0px;
}
iframe{
width:800px;
height:500px;
}
img{border:none;}
.parentDisabled
{
width:100%;
height:100%
background-color:red;
position:absolute;
top:0;
left:0;
display:block;
border:1px solid blue;
}
#popup{
position:absolute;
width:800px;
height:500px;
border:2px solid #999188;
display:none;
}
#header{
padding-right:0px;
width:800px;
}
#close{
cursor:hand;
width:15px;
position: absolute;
right:0;
top:0;
padding:2px 2px 0px 0px;
}
#move{
cursor:move;
background:#999188;
width:800px;
line-height:10px;
}
#container{
}
.navigate{
border:1px solid black ;
background:#CC00FF;
color:white;
padding:5px;
cursor:hand;
font-weight:bold;
width:150px;
}
</style>
</HEAD>
<BODY>
<div onClick="showPopUp('w3schools');" class="navigate">W3Schools</div>
<div onClick="showPopUp('yahoo');" class="navigate">Yahoo</div>
<div onClick="showPopUp('linkedin');" class="navigate">LinkedIn</div>
<div onClick="showPopUp('vistex');" class="navigate">Vistex</div>
<div id="popup">
<div id="header">
<span id="move"></span>
<span id="close"><img src="close_red.gif" onClick="closePopUp()" alt="Close"/></span>
</div>
<div id="container">
<iframe name="frame" id="Page_View" frameborder=0>
page cannot be displayed
</iframe>
</div>
</div>
</BODY>
<script>
var popUpEle=null;
function showPopUp(value,evt)
{
evt = evt ? evt : window.event;
var left=evt.clientX;
var top=evt.clientY;
popUpEle = document.getElementById('popup');
if(popUpEle)
{
closePopUp();
var url= "http://www."+value+".com";
document.getElementById('Page_View').src=url;
popUpEle.style.left=left;
popUpEle.style.top=top;
popUpEle.style.filter="revealTrans( transition=1, duration=1)";
popUpEle.filters.revealTrans( transition=1, duration=1).Apply();
popUpEle.filters.revealTrans( transition=1, duration=1).Play();
popUpEle.style.display="inline";
}
}
function closePopUp(){
if(popUpEle)
{
popUpEle.style.filter="revealTrans( transition=0, duration=4)";
popUpEle.filters.revealTrans( transition=0, duration=5).Apply();
popUpEle.filters.revealTrans( transition=0, duration=5).Play();
popUpEle.style.display="none";
}
}
var dragApproved=false;
var DragHandler = {
// private property.
_oElem : null,
// public method. Attach drag handler to an element.
attach : function(oElem) {
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin : function(e) {
var oElem = DragHandler._oElem = this;
if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
if (e.pageX || e.pageY)
{
oElem.mouseX = e.pageX;
oElem.mouseY = e.pageY;
}
else if (e.clientX || e.clientY) {
oElem.mouseX = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
oElem.mouseY = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
return false;
},
// private method. Drag (move) element.
_drag : function(e) {
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
var clientXTmp,clientYTmp;
if (e.pageX || e.pageY)
{
clientXTmp = e.pageX;
clientXTmp = e.pageY;
}
else if (e.clientX || e.clientY) {
clientXTmp = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
clientYTmp = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
var tmpX = x + (clientXTmp - oElem.mouseX);
var tmpY = y + (clientYTmp - oElem.mouseY);
if(tmpX<=0){tmpX = 0;}
if(tmpY<=0){tmpY = 0;}
oElem.style.left = tmpX + 'px';
oElem.style.top = tmpY + 'px';
oElem.mouseX = clientXTmp;
oElem.mouseY = clientYTmp;
return false;
},
// private method. Stop drag process.
_dragEnd : function()
{
var oElem = DragHandler._oElem;
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
}
}
DragHandler.attach(document.getElementById('popup'));</script>
</HTML>
First, your script didn't work in firefox or chrome so I did some changes.
Second, there's a limitation when moving the mouse very fast over the iframe. It seems that when the mouse is over an iframe, the 'mousemove' event isn't fired.
I inserted some fixes to your code and here it is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<style>
body
{
margin: 0px;
padding: 0px;
}
iframe
{
width: 800px;
height: 500px;
}
img
{
border: none;
}
.parentDisabled
{
width: 100%;
height: 100% background-color:red;
position: absolute;
top: 0;
left: 0;
display: block;
border: 1px solid blue;
}
#popup
{
position: absolute;
width: 800px;
height: 500px;
border: 2px solid #999188;
display: none;
}
#header
{
padding-right: 0px;
width: 800px;
height:20px;
background:#d8d8d8;
cursor:move;
}
#close
{
cursor: hand;
width: 15px;
position: absolute;
right: 0;
top: 0;
padding: 2px 2px 0px 0px;
}
#move
{
cursor: move;
background: #999188;
width: 800px;
line-height: 10px;
}
#container
{
}
.navigate
{
border: 1px solid black;
background: #CC00FF;
color: white;
padding: 5px;
cursor: hand;
font-weight: bold;
width: 150px;
}
</style>
</head>
<body>
<div onclick="showPopUp('w3schools', event);" class="navigate">
W3Schools</div>
<div onclick="showPopUp('yahoo', event);" class="navigate">
Yahoo</div>
<div onclick="showPopUp('linkedin', event);" class="navigate">
LinkedIn</div>
<div onclick="showPopUp('vistex', event);" class="navigate">
Vistex</div>
<div id="popup">
<div id="header">
<span id="move"></span><span id="close">
<img src="close_red.gif" onclick="closePopUp()" alt="Close" /></span>
</div>
<div id="container">
<iframe name="frame" id="Page_View" frameborder="0">page cannot be displayed </iframe>
</div>
</div>
<div id='log'></div>
<script type="text/javascript">
var popUpEle = null;
var isIE = navigator.appVersion.indexOf("MSIE") !== -1;
function showPopUp(value, evt)
{
evt = evt ? evt : window.event;
var left = evt.clientX;
var top = evt.clientY;
popUpEle = document.getElementById('popup');
if (popUpEle)
{
closePopUp();
var url = "http://www." + value + ".com";
document.getElementById('Page_View').src = url;
popUpEle.style.left = left;
popUpEle.style.top = top;
popUpEle.style.filter = "revealTrans( transition=1, duration=1)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 1, duration = 1).Apply();
popUpEle.filters.revealTrans(transition = 1, duration = 1).Play();
}
popUpEle.style.display = "block";
}
}
function closePopUp()
{
if (popUpEle)
{
popUpEle.style.filter = "revealTrans( transition=0, duration=4)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 0, duration = 5).Apply();
popUpEle.filters.revealTrans(transition = 0, duration = 5).Play();
}
popUpEle.style.display = "none";
}
}
var DragHandler = {
// private property.
_oElem: null,
_dragElement: null,
// public method. Attach drag handler to an element.
attach: function (oElem)
{
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin: function (e)
{
e = window.event || e;
var oElem = DragHandler._oElem = this;
// saving current mouse position
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;
// if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
// if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
// var x = parseInt(oElem.style.left);
// var y = parseInt(oElem.style.top);
// e = e ? e : window.event;
// if (e.pageX || e.pageY)
// {
// oElem.mouseX = e.pageX;
// oElem.mouseY = e.pageY;
// }
// else if (e.clientX || e.clientY)
// {
// oElem.mouseX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
// oElem.mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
// }
// saving the element which invoked the drag
// to capture 'mouseout' event
DragHandler._dragElement = document.elementFromPoint(e.clientX, e.clientY);
DragHandler._dragElement.onmouseout = DragHandler._dragMouseOut;
document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
return false;
},
_dragMouseOut: function (e)
{
e = window.event || e;
//document.getElementById("log").innerHTML += "mouseout!: " + e.clientX + "," + e.clientY + "<br/>";
// calculating move by
var oElem = DragHandler._oElem;
var moveByX = e.clientX - oElem.mouseX;
var moveByY = e.clientY - oElem.mouseY;
//if (document.getElementById("log").offsetHeight > 100)
//document.getElementById("log").innerHTML = "";
document.getElementById("log").innerHTML += "mouseout x: " + moveByX + ", y:" + moveByY + "<br/>";
// setting position
var futureX = (x + moveByX);
if (futureX < 0) futureX = 0;
var futureY = (y + moveByY);
if (futureY < 0) futureY = 0;
oElem.style.left = futureX + 'px';
oElem.style.top = futureY + 'px';
oElem.mouseX = e.clientX;
if (oElem.mouseX < 0) oElem.mouseX = 0;
oElem.mouseY = e.clientY;
if (oElem.mouseY < 0) oElem.mouseY = 0;
},
// private method. Drag (move) element.
_drag: function (e)
{
e = window.event || e;
var oElem = DragHandler._oElem;
document.getElementById("log").innerHTML += "mousemove!!!<br/>";
// current element position
var x = oElem.offsetLeft;
var y = oElem.offsetTop;
// calculating move by
var moveByX = e.clientX - oElem.mouseX;
var moveByY = e.clientY - oElem.mouseY;
//if (document.getElementById("log").offsetHeight > 100)
//document.getElementById("log").innerHTML = "";
document.getElementById("log").innerHTML += "mouse move x: " + moveByX + ", y:" + moveByY + "<br/>";
// setting position
var futureX = (x + moveByX);
if (futureX < 0) futureX = 0;
var futureY = (y + moveByY);
if (futureY < 0) futureY = 0;
oElem.style.left = futureX + 'px';
oElem.style.top = futureY + 'px';
oElem.mouseX = e.clientX;
if (oElem.mouseX < 0) oElem.mouseX = 0;
oElem.mouseY = e.clientY;
if (oElem.mouseY < 0) oElem.mouseY = 0;
// canceling selection
if (!isIE)
return false;
else
document.selection.empty();
},
// private method. Stop drag process.
_dragEnd: function ()
{
var oElem = DragHandler._oElem;
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
DragHandler._dragElement.onmouseout = null;
DragHandler._dragElement = null;
}
}
DragHandler.attach(document.getElementById('popup'));
</script>
</body></html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<style>
body
{
margin: 0px;
padding: 0px;
}
iframe
{
width: 400px;
height: 200px;
}
img
{
border: none;
}
.parentDisabled
{
width: 100%;
height: 100% background-color:red;
position: absolute;
top: 0;
left: 0;
display: block;
border: 1px solid blue;
}
#popup
{
position: absolute;
width: 400px;
height: 200px;
border: 2px solid #999188;
display: none;
}
#header
{
padding-right: 0px;
width: 400px;
height:20px;
background:#d8d8d8;
cursor:move;
}
#close
{
cursor: hand;
width: 15px;
position: absolute;
right: 0;
top: 0;
padding: 2px 2px 0px 0px;
}
#move
{
cursor: move;
background: #999188;
width: 400px;
line-height: 10px;
}
#container
{
}
.navigate
{
border: 1px solid black;
background: #CC00FF;
color: white;
padding: 5px;
cursor: hand;
font-weight: bold;
width: 150px;
}
</style>
</head>
<body>
<div onclick="showPopUp('w3schools', event);" class="navigate">
W3Schools</div>
<div onclick="showPopUp('yahoo', event);" class="navigate">
Yahoo</div>
<div onclick="showPopUp('linkedin', event);" class="navigate">
LinkedIn</div>
<div onclick="showPopUp('vistex', event);" class="navigate">
Vistex</div>
<div id="popup">
<div id="header">
<span id="move"></span><span id="close">
<img src="close_red.gif" onclick="closePopUp()" alt="Close" /></span>
</div>
<div id="container">
<iframe name="frame" id="Page_View" frameborder="0">page cannot be displayed </iframe>
</div>
</div>
<div id='log'></div>
</body>
<script>
var popUpEle = null;
var isIE = navigator.appVersion.indexOf("MSIE") !== -1;
function showPopUp(value, evt)
{
evt = evt ? evt : window.event;
var left = evt.clientX;
var top = evt.clientY;
popUpEle = document.getElementById('popup');
if (popUpEle)
{
closePopUp();
var url = "http://www." + value + ".com";
document.getElementById('Page_View').src = url;
popUpEle.style.left = left;
popUpEle.style.top = top;
popUpEle.style.filter = "revealTrans( transition=1, duration=1)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 1, duration = 1).Apply();
popUpEle.filters.revealTrans(transition = 1, duration = 1).Play();
}
popUpEle.style.display = "block";
}
}
function closePopUp()
{
if (popUpEle)
{
popUpEle.style.filter = "revealTrans( transition=0, duration=4)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 0, duration = 5).Apply();
popUpEle.filters.revealTrans(transition = 0, duration = 5).Play();
}
popUpEle.style.display = "none";
}
}
var dragApproved=false;
var DragHandler = {
// private property.
_oElem : null,
// public method. Attach drag handler to an element.
attach : function(oElem) {
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin : function(e) {
if (!document.all)return;
var oElem = DragHandler._oElem = this;
if (isNaN(parseInt(oElem.style.left))){ oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
if (e.pageX || e.pageY)
{
oElem.mouseX = e.pageX;
oElem.mouseY = e.pageY;
}
else if (e.clientX || e.clientY) {
oElem.mouseX = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
oElem.mouseY = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
document.onmousemove = DragHandler._drag;
dragApproved=true;
document.onmouseup = DragHandler._dragEnd;
return false;
},
// private method. Drag (move) element.
_drag : function(e) {
if(dragApproved && event.button==1)
{
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
var clientXTmp,clientYTmp;
if (e.pageX || e.pageY)
{
clientXTmp = e.pageX;
clientXTmp = e.pageY;
}
else if (e.clientX || e.clientY) {
clientXTmp = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
clientYTmp = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
var tmpX = x + (clientXTmp - oElem.mouseX);
var tmpY = y + (clientYTmp - oElem.mouseY);
if(tmpX<=0){tmpX = 0;}
if(tmpY<=0){tmpY = 0;}
//Avoiding scrolling of rigth and bottom of the window
if((tmpX+oElem.offsetWidth) > document.body.offsetWidth)
{
tmpX= document.body.offsetWidth-oElem.offsetWidth;
}
if((tmpY+oElem.offsetHeight) > document.body.offsetHeight)
{
tmpY= document.body.offsetHeight-oElem.offsetHeight;
}
oElem.style.left = tmpX + 'px';
oElem.style.top = tmpY + 'px';
oElem.mouseX = clientXTmp;
oElem.mouseY = clientYTmp;
return false;
}
},
// private method. Stop drag process.
_dragEnd : function()
{
dragApproved=false;
var oElem = DragHandler._oElem;
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
}
}
DragHandler.attach(document.getElementById('popup'));
</script>
</HTML>

Categories