I had created one div window which is draggable,and created one child div (with in the window div) which is scrollable.Those work individually fine,but when I am trying to scroll the inner div by clicking on up and down arrow of scroll, the drag event is triggered once scrolling has been finished.I am not able to solve the issue....Any suggestions please...
Here is the code...
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE> Reporting</TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<style>
body{
font-family:Arial,Helvetica,sans-serif;
font-size:0.7em;
}
.Object{
width:190px;
height:100px;
border:1px solid black;
border-radius:7px 7px 7px 7px;
box-shadow:3px 3px 2px #D2D2D2;
position:absolute;
resize:
}
.ObjHdr{
color:#fff;
background:#363636;
padding:3px 0px 3px 7px;
border-radius:6px 6px 0px 0px;;
font-weight:bold;
cursor:move;
}
.ObjBody{
width:190px;
height:77px;
overflow:scroll;
}
.ObjEle{
padding:1px 0px 1px 4px;
color:#000;
border-bottom:1px solid black;
cursor:pointer;
}
</style>
</HEAD>
<BODY>
<div id="ObjCountry" class="Object">
<div class="ObjHdr">Country</div>
<div id =sd class="ObjBody" unselectable="on">
<div class="ObjEle">India</div>
<div class="ObjEle">China</div>
<div class="ObjEle">USA</div>
<div class="ObjEle">Iran</div>
<div class="ObjEle">Iraq</div>
<div class="ObjEle">Indonesia</div>
</div>
</div>
</BODY>
</HTML>
<script>
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;
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;
oElem.dragBegin(oElem,x,y);
//document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
oElem.onmousemove = DragHandler._drag;
oElem.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 tmpX = x + (e.clientX - oElem.mouseX);
var tmpY = y + (e.clientY - oElem.mouseY);
if(tmpX<=0){tmpX = 0;}
if(tmpY<=0){tmpY = 0;}
oElem.style.left = tmpX + 'px';
oElem.style.top = tmpY + 'px';
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;
oElem.drag(oElem, x,y);
return false;
},
// private method. Stop drag process.
_dragEnd : function() {
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
oElem.dragEnd(oElem, x, y);
oElem.onmousemove = null;
oElem.onmouseup = null;
document.onmousemove=null;
document.onmouseup=null;
DragHandler._oElem = null;
}
}
DragHandler.attach(document.getElementById('ObjCountry'));
</script>
I would made it as follows:
-create a new method in draghandler which calls only the dragend private method
-create a mousedown event to id="ObjHdr" - it starts the dragging
-create a mouseup event to id="ObjHdr" - it ends the dragging
into draghandler:
detach: function(oElem) {oElem.onmousedown = DragHandler._dragEnd; return oElem; },
document.getElementById("ObjHdr").onmousedown="DragHandler.attach(document.getElementById("ObjCountry"));"
document.getElementById("ObjHdr").onmouseup="DragHandler.detach(document.getElementById("ObjCountry"));"
result:
Drag-drop event starts only if you click on the header and ends on mouseup.
No action if you try to click on "ObjBody" - no dragprocess will start..
regards
Ozsi
This is because, the drag is applicable all-through the div, including scroll bar. since it is invoked on mousedown, it is invoked on clicking scroll bar too.
Related
I'm trying to add collision detection in my draggable code which works pretty well I guess ,but when I'm trying to drag the orange rectangle above the green one nothing happens.
Is my collision logic right ?
Here is what I tried to do.
//HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href = "stl.css" rel = "stylesheet" type = "text/css">
</head>
<body>
<div class="item1"></div>
<div class="item2"></div>
<script src = "js.js" type = "text/javascript"></script>
</body>
</html>
I used getBoundingClientRect() to get the position of the rectangles.
//JAVASCRIPT code
const el1 = document.querySelector(".item1");
const el2 = document.querySelector(".item2");
var rect1,rect2;
rect2 = el2.getBoundingClientRect();
el1.addEventListener("mousedown", mousedown);
function mousedown(e) {
window.addEventListener("mousemove", mousemove);
window.addEventListener("mouseup", mouseup);
let prevX = e.clientX; // x cursor position
let prevY = e.clientY;//y cursor position
function mousemove(e) {
let newX = prevX - e.clientX;
let newY = prevY - e.clientY;
rect1 = el1.getBoundingClientRect();
el1.style.left = rect1.left - newX + "px";
el1.style.top = rect1.top - newY + "px";
prevX = e.clientX;
prevY = e.clientY;
//a simple rectangle collision logic funcion
if (rect1.left < rect2.left + rect2.weight &&
rect1.left + rect1.weight > rect2.left &&
rect1.top < rect2.top + rect2.height &&
rect1.height + rect1.top > rect2.top)
{
item2.style.color="#FF0006";
}
}
//function which stops the mousedown event
function mouseup() {
window.removeEventListener("mousemove", mousemove);
window.removeEventListener("mouseup", mouseup);
}
}
I know that item1 require absolute position for draggable action
//CSS code
.item1{
height:50px;
width:50px;
position:absolute;
background:orange;
}
.item2{
height:220px;
width:220px;
position:absolute;
background:green;
top:300px;
left:500px;
z-index:-2;
}
//JAVASCRIPT code
const el1 = document.querySelector(".item1");
const el2 = document.querySelector(".item2");
var rect1,rect2;
rect2 = el2.getBoundingClientRect();
el1.addEventListener("mousedown", mousedown);
function mousedown(e) {
window.addEventListener("mousemove", mousemove);
window.addEventListener("mouseup", mouseup);
let startX = e.clientX; // x cursor position
let startY = e.clientY; //y cursor position
const { left: rectX, top: rectY } = el1.getBoundingClientRect();
function mousemove(e) {
rect1 = el1.getBoundingClientRect();
const diffX = e.clientX - startX;
const diffY = e.clientY - startY;
el1.style.left = (rectX + diffX) + "px";
el1.style.top = (rectY + diffY) + "px";
// https://gamedev.stackexchange.com/questions/586/what-is-the-fastest-way-to-work-out-2d-bounding-box-intersection
// function IntersectRect(r1:Rectangle, r2:Rectangle):Boolean {
// return !(r2.left > r1.right
// || r2.right < r1.left
// || r2.top > r1.bottom
// || r2.bottom < r1.top);
// }
//a simple rectangle collision logic funcion
if (rect1.left < rect2.left + rect2.width &&
rect1.left + rect1.width > rect2.left &&
rect1.top < rect2.top + rect2.height &&
rect1.top + rect1.height > rect2.top)
{
el2.style.background ="#FF0006";
} else {
el2.style.background ="black"; // put original color
}
}
//function which stops the mousedown event
function mouseup() {
window.removeEventListener("mousemove", mousemove);
window.removeEventListener("mouseup", mouseup);
}
}
//CSS code
.body {
position: relative;
}
.item1{
height:50px;
width:50px;
position:absolute;
background:orange;
}
.item2{
height:120px;
width:120px;
position:absolute;
background:green;
top:300px;
left:500px;
z-index:-2;
}
//HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href = "stl.css" rel = "stylesheet" type = "text/css">
</head>
<body>
<div class="item1"></div>
<div class="item2"></div>
<script src = "js.js" type = "text/javascript"></script>
</body>
</html>
Practicing some front end stuff just by using addEventListener. What I am trying to achieve here is that : click the square and then hold the mouse while moving the square to another place on the page and stop moving by release the mouse. Something is not right as the square seems to move in one direction only. Need some help here.
#square_cursor {
position: relative;
left: 109px;
top: 109px;
height: 50px;
width: 50px;
background-color: rgb(219, 136, 136);
border: 5px rgb(136, 219, 219) solid;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Drop</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id='square_cursor'></div>
<script>
let mouse_over_detector = false; //move the mouse over WITHOUT clicking
let mouse_click_detector = false; //clicking the mouse WITHOUT moveover
let drag_detector = false; //move and holding the mouse together
let window_click_detector = false;
let window_motion_detector = false;
let position_x = 0;
let position_y = 0;
let new_position_x = 0;
let new_position_y = 0;
window.addEventListener('mousedown', () => {
window_click_detector = true;
})
window.addEventListener('mouseup', () => {
window_click_detector = false;
brick.style.backgroundColor = 'rgb(219, 136, 136)';
})
let brick = document.getElementById('square_cursor');
//done
brick.addEventListener('mousedown', (event) => {
position_x = event.clientX;
position_y = event.clientY;
mouse_click_detector = true;
brick.style.backgroundColor = 'yellow';
})
brick.addEventListener('mousemove', (event) => {
if (mouse_click_detector === true) {
new_position_x = event.clientX;
new_position_y = event.clientY;
dragAndDrop(position_x, position_y, event.offsetX, event.offsetY);
}
});
brick.addEventListener('mouseout', () => {
mouse_over_detector = false;
mouse_click_detector = false;
})
brick.addEventListener('mouseup', () => {
mouse_click_detector = false;
})
function dragAndDrop(a, b, c, d) {
console.log('new x: ')
console.log(a - c);
console.log('new y: ')
console.log(b - d);
brick.style.left = a - c + 'px'
brick.style.top = b - d + 'px';
}
</script>
</body>
</html>
SOLVED IT THIS MORNING by using just addEventListener wooohoooo!
So the keys here are, first, being able to identify the DOM hierarchy and second, knowing what clientX does for the selected element. I am going to post my solution in snippet mode.
But I am still gonna give a vote to the 1st answer.
#square_cursor{
position:absolute;
left:109px;
top:109px;
height:50px;
width:50px;
background-color: rgb(219, 136, 136);
border:5px rgb(136, 219, 219) solid;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Drop</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id='square_cursor'></div>
<script>
let mouse_click_detector = false; //clicking the mouse WITHOUT moveover
let window_click_detector = false;
let position_x = 0;
let position_y = 0;
let click_position_x = 0;
let click_position_y = 0;
let brick = document.getElementById('square_cursor');
brick.addEventListener('mousedown', () => {
mouse_click_detector = true
})
window.addEventListener('mouseup', () => {
mouse_click_detector = false;
window_click_detector = false;
brick.style.backgroundColor = 'rgb(219, 136, 136)';
})
window.addEventListener('mousedown', (event) => {
if (mouse_click_detector === true) {
window_click_detector = true;
brick.style.backgroundColor = 'yellow';
click_position_x = event.offsetX;
click_position_y = event.offsetY;
}
})
window.addEventListener('mousemove', (event) => {
if (mouse_click_detector === true) {
position_x = event.clientX;
position_y = event.clientY;
brick.style.left = position_x - click_position_x + 'px';
brick.style.top = position_y - click_position_y + 'px';
}
})
</script>
</body>
</html>
"The most personal is the most creative" --- Martin Scorsese
Something like this..
//Make the DIV element draggable:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
var 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;
}
}
#mydiv {
position: absolute; /* NECESSARY */
background-color: dodgerblue;
border: 1px solid #d3d3d3;
height: 20px;
width: 20px;
}
<div id="mydiv">
</div>
Minimalist code,
with simplified calculations by transform: translate(x,y).
const myDiv = document.querySelector('#my-div');
myDiv.ref_ms = { x: 0, y: 0 };
myDiv.addEventListener('mousedown', (e) =>
{
myDiv.ref_ms.x = e.clientX;
myDiv.ref_ms.y = e.clientY;
myDiv.classList.add('movCursor')
if (myDiv.style.transform !== '')
{
let [ mx, my ] = myDiv.style.transform.match(/-?\d*\.?\d+/g).map(Number);
myDiv.ref_ms.x -= mx;
myDiv.ref_ms.y -= my;
}
})
window.addEventListener('mousemove', e =>
{
if (myDiv.classList.contains('movCursor')
&& e.clientX > 0 && e.clientY > 0 )
{
myDiv.style = `transform: translate(${e.clientX - myDiv.ref_ms.x}px, ${e.clientY - myDiv.ref_ms.y}px);`;
}
})
window.addEventListener('mouseup', () =>
{
myDiv.classList.remove('movCursor')
})
#my-div {
background : dodgerblue;
border : 1px solid #d3d3d3;
height : 50px;
width : 50px;
margin : 30px;
cursor : grab;
}
.movCursor {
cursor : grabbing !important;
}
<div id="my-div"></div>
I would like to use HTML/CSS/JS to have a <div> change its colour only up to a certain width. This certain length depends on where it is clicked inside the <div>.
Example:
I would give code, but it would just be of a <div>.
I don't know how to use CSS/JS to detect where the mouse clicks on <div> (i.e. on what width size).
You can achieve this like this
function changeWidth(event) {
let outerDiv = document.getElementById('outerDiv');
document.getElementById('innerDiv').style.width = event.clientX-outerDiv.offsetLeft+'px';
}
#outerDiv {
width: 400px;
height:200px;
border: 1px solid black;
}
#innerDiv {
width: 0px;
height: 200px;
background-color: red;
}
<div id = 'outerDiv' onclick = 'changeWidth(event)'>
<div id = 'innerDiv' ></div>
</div>
You have keep in check the position of the outerbox which you can get by using el.offSetLeft
A simple approach using background-image to create the color.
document.querySelector(".box").addEventListener("click", function(e){
var position = e.clientX - this.getBoundingClientRect().left;
this.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
});
.box {
border: 2px solid #c3c3c3;
height: 200px;
width: 400px;
}
<div class="box"></div>
e.clientX is the position relative to the window. So you can use the left position of the div from .getBoundingClientRect().left and subtract it to get the exact click position.
If you need this to work for multiple divs:
1) Add inline onclick to each <div>
function colourBackground (e, div) {
var position = e.clientX - div.getBoundingClientRect().left;
div.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
};
.box {
border: 2px solid #c3c3c3;
height: 200px;
width: 400px;
}
<div class="box" onclick="colourBackground(event, this)"></div>
<div class="box" onclick="colourBackground(event, this)"></div>
<div class="box" onclick="colourBackground(event, this)"></div>
Or 2) Use a forEach loop to add a click event to each <div>
document.querySelectorAll(".box").forEach(function(div) {
div.addEventListener("click", function(e){
var position = e.clientX - div.getBoundingClientRect().left;
div.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
});
})
.box {
border: 2px solid #c3c3c3;
height: 200px;
width: 400px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
I would do like:
//<![CDATA[
/* js/external.js */
let get, post, doc, html, bod, nav, M, I, mobile, S, Q, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
x.send();
}
post = function(url, send, success, context){
const x = new XMLHttpRequest;
const c = context || x;
x.open('POST', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
if(typeof send === 'object' && send && !(send instanceof Array)){
if(send instanceof FormData){
x.send(send);
}
else{
const fd = new FormData;
for(let k in send){
fd.append(k, JSON.stringify(send[k]));
}
x.send(fd);
}
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
// you can ignore most of the above code (but it's useful, so keep it) - put below on a separate page on another load - except the load end
const block = I('block'), colorStyle = block.firstChild.style;
let down = false;
function colorIt(e){
if(down)colorStyle.width = e.clientX-e.target.offsetLeft+'px';
}
function touchMode(){
block.onmousedown = block.onmousemove = undefined;
block.ontouchstart = e=>{
down = true; colorIt(e.touches[0]);
}
block.ontouchmove = e=>{
colorIt(e.touches[0]);
}
}
function mouseMode(){
block.ontouchstart = block.ontouchmove = undefined;
block.onmousedown = e=>{
down = true; colorIt(e);
}
block.onmousemove = colorIt;
}
block.onclick = ()=>{
down = false;
}
if(mobile){
touchMode();
}
else{
mouseMode();
}
}); // load end
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%; background:#ccc;
}
.main{
padding:10px;
}
#block{
width:200px; height:75px; background:#fff; border:1px solid #000; cursor:pointer;
}
#block>div{
width:0; height:100%; background:green;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div id='block'><div></div></div>
</div>
</body>
</html>
Interesting question.
First, use this to get the location of your div: https://stackoverflow.com/a/10445639/11444910
Then get your mouse position on click: https://stackoverflow.com/a/23744762/11444910
Now that you can tell where your div is and where your mouse is when clicked, you should be able to tell if you are clicking inside of the div or not. Then it's a matter of applying the Y location of your mouse to the div, and using that to inform the color change.
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.
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>