How do I convert global coordinates to local? - javascript

I have created some simple drag and drop. (There's some junk in the code that seems like it ought to be useful.)
Html:
<div id="container">
<div id="target"></div>
</div>
Javascript:
var el = document.getElementById('target');
var mover = false,
x, y, posx, posy, first = true;
el.onmousedown = function () {
mover = true;
};
document.onmouseup = function () {
mover = false;
first = false;
};
document.onmousemove = function (e) {
if (mover) {
e = e || window.event;
var target = e.srcElement || e.target;
var rect = target.getBoundingClientRect();
if (first) {
first = false;
x = (getMouseCoordinates(e).x - rect.left);
y = (getMouseCoordinates(e).y - rect.top);
}
posx = getMouseCoordinates(e).x;// - x;
posy = getMouseCoordinates(e).y;// - y;
el.style.left = posx + 'px';
el.style.top = posy + 'px';
}
};
function getMouseCoordinates(e) {
e = e || window.event;
var pageX = e.pageX;
var pageY = e.pageY;
if (pageX === undefined) {
pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return {
x: pageX,
y: pageY
}
}
CSS:
#target {
left: 50px;
top: 50px;
width: 150px;
height: 100px;
background-color: #ffc;
position: absolute;
}
#container {
left: 30px;
top:30px;
width: 300px;
height: 300px;
background-color: red;
position: absolute;
}
http://jsfiddle.net/YGzm6/
The problem is that the draggable is inside a container that is positioned. So when I position the draggable with the mouse's global co-ordinates, the draggable is actually being positioned relative to its non global container.
So how do I translate the co-ordinates such that the draggable doesn't jump about? Surely I need to know the offset of the parent container?

var x = 0, y = 0;
var element = document.getElementById('container');
do {
x += element.offsetLeft;
y += element.offsetTop;
}
while (element = element.offsetParent);

Related

How to save drag and drop to local storage?

I'm just learning JavaScript. There is a code that can move the block. But I can't save it in localStorage. Help!
let drag = document.querySelector('.note');
drag.onmousedown = function(e) {
let coord = getCoord(drag);
let shiftX = e.pageX - coord.left;
let shiftY = e.pageY - coord.top;
drag.style.position = 'absolute';
document.body.appendChild(drag);
moveNote(e);
drag.style.zIndex = 1000;
function moveNote(e) {
drag.style.left = e.pageX - shiftX + 'px';
drag.style.top = e.pageY - shiftY + 'px';
}
document.onmousemove = function(e) {
moveNote(e);
};
drag.onmouseup = function() {
document.onmousemove = null;
drag.onmouseup = null;
};
}
function getCoord(elem) {
let main = elem.getBoundingClientRect();
return {
top: main.top,
left: main.left
};
}
.note {
width: 50px;
height: 50px;
background: red;
}
<div class="note">
</div>
This seems like very simple process.
On mouse up, get the left and top properties and save their values to localStorage:
document.addEventListener("mouseup", () => {
localStorage.setItem("top", drag.style.top);
localStorage.setItem("left", drag.style.top);
});
let coordinates = localStorage["top"] + "," + localStorage["left"];
if (localStorage["top"] && localStorage["left"]) {
drag.style.top = coordinates.split(",")[0];
drag.style.left = coordinates.split(",")[1];
}
Or the quicker way
document.addEventListener("mouseup", () => {
localStorage.setItem("coordinates", drag.style.top + "," + drag.style.left);
});
let coordinates = localStorage["coordinates"];
if (localStorage["coordinates"]) {
drag.style.top = coordinates.split(",")[0];
drag.style.left = coordinates.split(",")[1];
}
You can save the location using localStorge.setItem("key", "value") and load the item using localStorge.getItem("key"). So we save the JSON representation of our location object. We do that when mouse is up. But also not forgetting to load the value first on page load.
Note: This won't work in this sandbox environment.
let drag = document.querySelector('.note');
drag.onmousedown = function(e) {
let coord = getCoord(drag);
let shiftX = e.pageX - coord.left;
let shiftY = e.pageY - coord.top;
drag.style.position = 'absolute';
document.body.appendChild(drag);
moveNote(e);
drag.style.zIndex = 1000;
function moveNote(e) {
drag.style.left = e.pageX - shiftX + 'px';
drag.style.top = e.pageY - shiftY + 'px';
var position = {
x: drag.style.left,
y: drag.style.top
}
localStorage.setItem("last-position", JSON.stringify(position))
}
document.onmousemove = function(e) {
moveNote(e);
};
drag.onmouseup = function() {
document.onmousemove = null;
drag.onmouseup = null;
};
}
function getCoord(elem) {
let main = elem.getBoundingClientRect();
return {
top: main.top,
left: main.left
};
}
window.onload = function() {
var str_position = localStorage.getItem("last-position") || "{x:0, y:0}"
var position = JSON.parse(str_position);
drag.style.left = position.x;
drag.style.top = position.y;
drag.style.position = 'absolute';
document.body.appendChild(drag);
drag.style.display = 'block'
}
.note {
width: 50px;
height: 50px;
background: red;
display: none;
}
<div class="note">
</div>

Move element with mouse starts to snap up and down

I am trying to make a drag on y axis functionality using mousedown, mousemove events. The formula is as follows:
var position = e.clientY - getOrigin(myDiv).top;
myDiv.style.transform = 'translate3d(0px, ' + position + 'px, 0px)';
function getOrigin(elm) {
...
return {
left: box.left + (win.pageXOffset || docElem.scrollLeft) - clientLeft,
top: box.top + (win.pageYOffset || docElem.scrollTop) - clientTop
};
}
When I drag the element, it snaps up and down really fast. Why is that happening, and how can I fix it?
JSFiddle
var myDiv = document.getElementById('myDiv');
myDiv.addEventListener('mousedown', handleMouseDown);
window.addEventListener('mouseup', handleMouseUp);
function handleMouseDown(e) {
window.addEventListener('mousemove', handleMouseMove);
}
function handleMouseUp(e) {
window.removeEventListener('mousemove', handleMouseMove);
}
function handleMouseMove(e) {
e.preventDefault();
var position = e.clientY - getOrigin(myDiv).top;
myDiv.style.transform = 'translate3d(0px, ' + position + 'px, 0px)';
}
function getOrigin(elm) {
var box = (elm.getBoundingClientRect) ? elm.getBoundingClientRect() : {
top: 0,
left: 0
},
doc = elm && elm.ownerDocument,
body = doc.body,
win = doc.defaultView || doc.parentWindow || window,
docElem = doc.documentElement || body.parentNode,
clientTop = docElem.clientTop || body.clientTop || 0, // border on html or body or both
clientLeft = docElem.clientLeft || body.clientLeft || 0;
return {
left: box.left + (win.pageXOffset || docElem.scrollLeft) - clientLeft,
top: box.top + (win.pageYOffset || docElem.scrollTop) - clientTop
};
}
body {
margin-top: 50px;
padding-top: 50px;
}
#myDiv {
background-color: orange;
width: 200px;
height: 100px;
}
<div id="myDiv"></div>
Because I couldn't exactly figure out what was causing the problem in OPs question (for an unknown reason box.top was returning 2 different values alternately on each pixel movement in OPs script), I've written a different script that works perfectly fine:
//document.addEventListener('DOMContentLoaded', function(){
var myDiv = document.getElementById('myDiv');
myDiv.addEventListener('mousedown', handleMouseDown);
window.addEventListener('mouseup', handleMouseUp);
function handleMouseDown(e) {
window.addEventListener('mousemove', mouseMove.start(this, 'body',e));
}
function handleMouseUp(e) {
window.removeEventListener('mousemove', mouseMove.stop('body'));
}
var mouseMove = function(){
return {
move: function(elm, posY){
elm.style.top = posY + "px";
},
start: function(elm, container, e){
e = e || window.event;
var posY = e.clientY,
elmTop = elm.style.top,
elmHeight = parseInt(elm.style.height),
conHeight = parseInt(document.getElementById(container).style.height);
elmTop = elmTop.replace('px','');
var diffY = posY - elmTop;
document.onmousemove = function(e){
e = e || window.event;
var posY = e.clientY,
Y = posY - diffY;
if (Y < 0) Y = 0;
if (Y + elmHeight > conHeight) Y = conHeight - elmHeight;
mouseMove.move(elm,Y);
}
},
stop : function(container){
var a = document.createElement('script');
document.onmousemove = function(){}
},
}
}();
//});
#body {
margin-top: 50px;
position: absolute;
}
#myDiv {
position: absolute;
background-color: orange;
width: 200px;
height: 100px;
}
<div id="body">
<div id="myDiv"></div>
</div>

Drag an HTML box and make another box follow it with JavaScript

I am trying to create something like drag a box (Hello World) to any location, and the second box (Follow World) will follow slowly.
In the code below, the drag box is fine, but the follow box will not follow properly. Also, the drag box cannot drop.
function startDrag(e) {
// determine event object
if (!e) {
var e = window.event;
}
// IE uses srcElement, others use target
var targ = e.target ? e.target : e.srcElement;
if (targ.className != 'dragme') {
return
};
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// assign default values for top and left properties
if (!targ.style.left) {
targ.style.left = '0px'
};
if (!targ.style.top) {
targ.style.top = '0px'
};
// calculate integer values for top and left
// properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
// move div element
document.onmousemove = dragDiv;
return false;
}
function dragDiv(e) {
if (!drag) {
return
};
if (!e) {
var e = window.event
};
var targ = e.target ? e.target : e.srcElement;
// move div element
targ.style.left = coordX + e.clientX - offsetX + 'px';
targ.style.top = coordY + e.clientY - offsetY + 'px';
return false;
}
function stopDrag() {
timer();
drag = false;
}
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function disp() {
var step = 1;
var y = document.getElementById('followme').offsetTop;
var x = document.getElementById('followme').offsetLeft;
var ty = document.getElementById('draggable').offsetTop;
var ty = document.getElementById('draggable').offsetLeft;
if (y < ty) {
y = y + step;
document.getElementById('followme').style.top = y + "px"; // vertical movment
} else {
if (x < tx) {
x = x + step;
document.getElementById('followme').style.left = x + "px"; // horizontal movment
}
}
}
function timer() {
disp();
var y = document.getElementById('followme').offsetTop;
var x = document.getElementById('followme').offsetLeft;
document.getElementById("msg").innerHTML = "X: " + tx + " Y : " + ty
my_time = setTimeout('timer()', 10);
}
.dragme {
position: relative;
width: 60px;
height: 80px;
cursor: move;
}
.followme {
position: relative;
width: 60px;
height: 80px;
}
#draggable {
background-color: #ccc;
border: 1px solid #000;
}
#followme {
background-color: #ccc;
border: 1px solid #000;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and drop</title>
</head>
<body>
<div id='msg'></div>
<div id="draggable" class="dragme">"Hello World!"</div>
<div id="followme" class="followme">"Follow World!"</div>
Fix yours disp and timer functions to this:
function disp()
{
var step = 1;
// in dragDiv() you modifying style.left/style.top properties, not offsetTop/offsetLeft
var x = parseInt(document.getElementById('followme').style.left) || 0;
var y = parseInt(document.getElementById('followme').style.top) || 0;
var tx = parseInt(document.getElementById('draggable').style.left) || 0;
var ty = parseInt(document.getElementById('draggable').style.top) || 0;
// properly calculate offset
var dx = ((dx = tx - x) == 0) ? 0 : Math.abs(dx) / dx;
var dy = ((dy = ty - y) == 0) ? 0 : Math.abs(dy) / dy;
document.getElementById('followme').style.left = (x + dx * step) + "px"; // horisontal movment
document.getElementById('followme').style.top = (y + dy * step) + "px"; // vertical movment
}
function timer()
{
disp();
var y=document.getElementById('followme').offsetTop;
var x=document.getElementById('followme').offsetLeft;
document.getElementById("msg").innerHTML="X: " + x + " Y : " + y; // typo was here
my_time = setTimeout(function () {
clearTimeout(my_time); // need to clear timeout or it'll be adding each time 'Hello world' clicked
timer();
},10);
}
In the following snippet, the pink box is draggable and the blue box follows it around. You can change pixelsPerSecond to adjust the speed of movement.
function message(s) {
document.getElementById('messageContainer').innerHTML = s;
}
window.onload = function () {
var pixelsPerSecond = 80,
drag = document.getElementById('drag'),
follow = document.getElementById('follow'),
wrapper = document.getElementById('wrapper'),
messageContainer = document.getElementById('messageContainer'),
leftMax,
topMax;
function setBoundaries() {
leftMax = wrapper.offsetWidth - drag.offsetWidth;
topMax = wrapper.offsetHeight - drag.offsetHeight;
drag.style.left = Math.min(drag.offsetLeft, leftMax) + 'px';
drag.style.top = Math.min(drag.offsetTop, topMax) + 'px';
}
setBoundaries();
window.onresize = setBoundaries;
[drag, follow, messageContainer].forEach(function (element) {
element.className += ' unselectable';
element.ondragstart = element.onselectstart = function (event) {
event.preventDefault();
};
});
var start = Date.now();
drag.onmousedown = function (event) {
event = event || window.event;
var x0 = event.pageX || event.clientX,
y0 = event.pageY || event.clientY,
left0 = drag.offsetLeft,
top0 = drag.offsetTop;
window.onmousemove = function (event) {
var x = event.pageX || event.clientX,
y = event.pageY || event.clientY;
drag.style.left = Math.max(0, Math.min(left0 + x - x0, leftMax)) + 'px';
drag.style.top = Math.max(0, Math.min(top0 + y - y0, topMax)) + 'px';
};
window.onmouseup = function () {
window.onmousemove = window.onmouseup = undefined;
};
};
follow.x = follow.offsetLeft;
follow.y = follow.offsetTop;
function update() {
var elapsed = Date.now() - start;
if (elapsed === 0) {
window.requestAnimationFrame(update);
return;
}
var x1 = drag.offsetLeft,
y1 = drag.offsetTop + (drag.offsetTop + drag.offsetHeight <= topMax ?
drag.offsetHeight : -drag.offsetHeight),
x0 = follow.x,
y0 = follow.y,
dx = x1 - x0,
dy = y1 - y0,
distance = Math.sqrt(dx*dx + dy*dy),
angle = Math.atan2(dy, dx),
dd = Math.min(distance, pixelsPerSecond * elapsed / 1000);
message('x: ' + x1 + ', y: ' + y1);
follow.x += Math.cos(angle) * dd;
follow.style.left = follow.x + 'px';
follow.y += Math.sin(angle) * dd;
follow.style.top = follow.y + 'px';
start = Date.now();
window.requestAnimationFrame(update);
}
window.requestAnimationFrame(update);
};
#wrapper {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #eee;
font-family: sans-serif;
text-align: center;
}
.unselectable {
-webkit-user-select: none;
-khtml-user-drag: none;
-khtml-user-select: none;
-moz-user-select: none;
-moz-user-select: -moz-none;
-ms-user-select: none;
user-select: none;
}
#messageContainer {
position: absolute;
left: 80px;
top: 50px;
font-size: 36px;
color: #aaa;
cursor: default;
}
.box {
position: absolute;
width: 60px;
height: 80px;
}
.label {
margin: 30px auto;
font-size: 14px;
}
#drag {
left: 100px;
top: 120px;
background: #f0dddb;
border: 2px solid #deb7bb;
cursor: move;
}
#follow {
left: 0;
top: 0;
background-color: #ddebf3;
border: 2px solid #bfd5e1;
cursor: default;
}
<div id="wrapper">
<div id="messageContainer"></div>
<div class="box" id="follow"> <div class="label">it follows</div> </div>
<div class="box" id="drag"> <div class="label">drag me</div> </div>

How to spoof dragging all elements of the same class with javascript?

I'm trying to make it so that a bunch of elements will move when the user holds down their mouse button and then drags the mouse. I'm trying to do this by listening to the mousedown and mousemove events and comparing their locations. The difference in the locations of is used to calculate how far to move all of the elements. The goal is that it will feel like all of the elements have been dragged. For some reason though, my approach results in the elements flying all over the place.
Here's an example of what I'm trying to do:
window.onload = function(){
var mouse = {isDown : false, lastX : null, lastY : null };
document.body.addEventListener("click", function(event){
var el = document.createElement("div");
el.className = "box";
el.style.left = event.clientX + "px";
el.style.top = event.clientY + "px";
el.style.backgroundColor = "BLACK";
el.style.width = "16px";
el.style.height = "16px";
el.style.position = "absolute";
document.body.appendChild(el);
});
document.body.addEventListener("mousedown", function(event){
mouse.isDown = true;
mouse.lastX = event.clientX;
mouse.lastY = event.clientY;
});
document.body.addEventListener("mouseup", function(){
mouse.isDown = false;
mouse.lastX = null;
mouse.lastY = null;
});
var removePx = function(string){return string.substring(0, string.length -2);}
document.body.addEventListener("mousemove", function(event){
console.log("move (" + event.clientX + "," + event.clientY + ")");
if(mouse.isDown){
var deltaX = event.clientX - mouse.lastX;
var deltaY = event.clientY - mouse.lastY;
console.log("DeltaX " + deltaX);
console.log("DeltaY " + deltaY);
var boxes = document.getElementsByClassName("box");
for(var i = 0; i<boxes.length; i++){
var box = boxes[i];
box.style.left = removePx(box.style.left) + deltaX + "px";
box.style.top = removePx(box.style.top) + deltaY + "px";
}
mouse.lastX = event.clientX;
mouse.lastY = event.clientY;
}
});
}
What's going wrong here? Also, is there a better way to accomplish this?
Regarding your code, i'd say that transform is preferrable regarding positioning for this kind of thing (instead of left/top) - see the discussion http://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/.
Anyway, i didn't take a closer look at your code, but instead, tried a solution myself to what i understood of it. I just used a simple pattern regarding drag and drop which is:
onmousedown - setState to moving, store the clicked point, get the current matrix of the transformation applied
onmousemove - calculate dx, dy, accumulate this differences in the matrix, update current x and y in the state
onmouseup - just remove the moving state
Here's a snippet:
var main = document.querySelector('main');
var movable = [].slice.call(document.querySelectorAll('.movable'));
var _state = {
x: 0,
y: 0,
matrix: [1, 0, 0, 1, 0, 0],
moving: false
};
movable.forEach(function (elem) {
elem.style.transform = 'matrix(' + _state.matrix.join(',') + ')'
});
function onMouseDown (e) {
_state.moving = true;
_state.x = e.clientX;
_state.y = e.clientY;
_state.matrix = matrixToArray(e.target.style.transform);
}
function matrixToArray (matrix) {
return matrix
.match(/matrix\((.*)\)/)[1]
.split(' ')
.join('')
.split(',')
.map(function (a) {
return +a;
});
}
function onMouseMove (e) {
if (!_state.moving)
return;
var dx = e.clientX - _state.x;
var dy = e.clientY - _state.y;
_state.matrix[4] += dx;
_state.matrix[5] += dy;
var transf = 'matrix(' + _state.matrix.join(',') + ')'
movable.forEach(function (elem) {
elem.style.transform = transf;
});
_state.x = e.clientX;
_state.y = e.clientY;
}
function onMouseUp (e) {
_state.moving = false;
_state.x = e.clientX;
_state.y = e.clientY;
}
main.addEventListener('mousemove', onMouseMove);
main.addEventListener('mouseup', onMouseUp);
movable.forEach(function (elem) {
elem.addEventListener('mousedown', onMouseDown);
});
html,
body,
main {
width: 100%;
height: 100%;
}
div {
width: 50px;
height: 50px;
position: absolute;
}
#d1 { background: black; left: 10px; top: 10px;}
#d2 { background: brown; left: 70px; top: 10px;}
#d3 { background: green; left: 10px; top: 70px ;}
#d4 { background: purple; left: 70px; top: 70px ;}
<main>
<div id="d1" class="movable"></div>
<div id="d2" class="movable"></div>
<div id="d3" class="not-movable"></div>
<div id="d4" class="movable"></div>
</main>
ps.: this is not all that much efficient. One can surely iterate on this and create a better version of it!

Why my javascript drag resize box doesn't work as expected

This is my code. I prefer to create a resize box purely on javascript without jquery.The code enable me to resize the width of paragraph when i drag it over but it seems like it don't work as expected.
<html>
<head>
<style>
div{
border: 1px solid black;
width: 500px;
height: 500px;
padding: 0px;
margin: 0px;
}
p{
border: 1px solid red;
position: absolute;
height: 200px;
width: 200px;
padding: 0px;
margin: 0px;
}
</style>
<script>
window.onload = function(){
document.body.onmousedown = function(event){
var mouseStartX = event.clientX;
var mouseStartY = event.clientY;
var div = document.getElementsByTagName("div");
var para = document.createElement("p");
div[0].appendChild(para);
document.styleSheets[0].cssRules[1].style.top = mouseStartY;
document.styleSheets[0].cssRules[1].style.left = mouseStartX;
document.body.onmousemove = function(event){
if(para){
document.styleSheets[0].cssRules[1].style.width = event.clientY - mouseStartY;
}
}
document.body.onmouseup = function(){
div[0].removeChild(para);
}
};
};
</script>
</head>
<body>
<div>
</div>
</body>
</html>
my problem is I expect that the p will keep on enlarge as I drag my mouse to the right,but it only work when I drag to a certain point
I can only attempt to answer your question because your wording is a bit vague. However, I copy and pasted your code into a test HTML file that I loaded into my web browser, and I can guess what the problem that you're having is. The problem is that the p enlarges as you drag your cursor, but it doesn't enlarge all the way so that the right border is in line with your cursor.
First of all, in your document.body.onmousemove function:
document.body.onmousemove = function (event) {
if (para) {
document.styleSheets[0].cssRules[1].style.width = event.clientY - mouseStartY;
}
}
You wrote event.clientY and mouseStartY when I think that you meant event.clientX and mouseStartX. However, you are also modifying a CSS rule, so you have to append the unit px to the end of the width:
document.body.onmousemove = function (event) {
if (para) {
document.styleSheets[0].cssRules[1].style.width = (event.clientX - mouseStartX) + "px";
// The parentheses are technically not required; I put them there for clarity.
}
}
The same goes for these two lines of code:
document.styleSheets[0].cssRules[1].style.top = mouseStartY;
document.styleSheets[0].cssRules[1].style.left = mouseStartX;
You forgot to include the units. Just add + "px" before the end of each line:
document.styleSheets[0].cssRules[1].style.top = mouseStartY + "px";
document.styleSheets[0].cssRules[1].style.left = mouseStartX + "px";
Additionally, it is better just to delete window.onmousemove and window.onmouseup in your window.onmouseup function instead of checking for para in your window.onmousemove function. Even after you remove para from the div, it still evaluates to true.
Finally, instead of modifying the stylesheet via document.styleSheets[0].cssRules[1], you could just directly edit the style of para by using para.style.width instead of document.styleSheets[0].cssRules[1].style.width.
I rewrote your window.onload function like this:
window.onload = function(){
document.body.onmousedown = function(event){
var mouseStartX = event.clientX,
mouseStartY = event.clientY,
div = document.getElementsByTagName("div"),
para = document.createElement("p");
div[0].appendChild(para);
para.style.top = mouseStartY + "px";
para.style.left = mouseStartX + "px";
document.body.onmousemove = function(event){
para.style.width = event.clientX - mouseStartX + "px";
//para.style.height = event.clientY - mouseStartY + "px";
// Uncomment the line above if you want to drag the height, too.
}
document.body.onmouseup = function(){
div[0].removeChild(para);
document.body.onmousemove = null;
document.body.onmouseup = null;
}
};
};
Use:
document.body.onmousemove = function (event) {
if (para) {
document.styleSheets[0].cssRules[1].style.width = event.clientX - mouseStartX;
}
}
instead of:
document.body.onmousemove = function (event) {
if (para) {
document.styleSheets[0].cssRules[1].style.width = event.clientY - mouseStartY;
}
}
Otherwise, the p element will only resize on vertical movement, not horizontal.
Cross-browser compatible solution also using window scroll offset and mouse movement in all four quadrants:
window.onload = function () {
var div = document.getElementsByTagName("div")[0];
var para = null, mouseStartX, mouseStartY; //top & left coordinates of paragraph
document.body.onmousedown = function (event) {
if (para) {
return;
}
event = event || window.event; // for IE8/7 http://stackoverflow.com/questions/7790725/javascript-track-mouse-position#7790764
// https://developer.mozilla.org/en-US/docs/Web/API/window.scrollY#Notes
var scrollX = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
var scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
mouseStartX = event.clientX + scrollX;
mouseStartY = event.clientY + scrollY;
para = document.createElement("p");
div.appendChild(para);
para.style.top = mouseStartY + 'px';
para.style.left = mouseStartX + 'px';
para.style.width = '0px';
para.style.height = '0px';
};
document.body.onmousemove = function (event) {
if (!para) {
return;
}
event = event || window.event;
var scrollX = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
var scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
var mouseCurrentX = event.clientX + scrollX;
var mouseCurrentY = event.clientY + scrollY;
if (mouseCurrentX >= mouseStartX) {
para.style.left = mouseStartX + 'px';
para.style.width = (mouseCurrentX - mouseStartX) + 'px';
} else {
para.style.left = mouseCurrentX + 'px';
para.style.width = (mouseStartX - mouseCurrentX) + 'px';
}
if (mouseCurrentY >= mouseStartY) {
para.style.top = mouseStartY + 'px';
para.style.height = (mouseCurrentY - mouseStartY) + 'px';
} else {
para.style.top = mouseCurrentY + 'px';
para.style.height = (mouseStartY - mouseCurrentY) + 'px';
}
};
document.body.onmouseup = function () {
div.removeChild(para);
para = null;
};
};
http://jsfiddle.net/hMbCF/1/
http://jsfiddle.net/hMbCF/1/show/

Categories

Resources