Grab Dynamically Added Content - javascript

Full code can be viewed on JSBin - http://jsbin.com/ecuraQEg/1/edit
I'm working on an experimental website designer (a wysiwyg editor) and I'm having a bit of trouble.
I want to be able to manipulate divs that have been drawn/appended, via changing it's position, background color, border, padding, etc:
Say I drew 3 divs with the following background color red, green, and blue.
When I click on the red div I want it to display all it's properties, height, width, top, left, background, etc: I already have width and height down, but I can't seem to figure out how to grab the other styles.
Any help is greatly appreciated.
DIVs width/height are grabbed by the following:
canvas.onmousemove = function(e) {
if ($('select#tools option:selected').val() !== 'select') return;
$('#canvas div').on('mousemove', function() {
// Detects/Shows div size on specified element.
$('#elm-width').val($(this).width().toString() + 'px');
$('#elm-height').val($(this).height().toString() + 'px');
});
document.getSelection().removeAllRanges();
$('#canvas div.rect').draggable();
code.val(preview.html());
coder.val(preview.html());
};
DIVs are drawn using the following JQuery/Javascript:
setMousePosition = function(e) {
if ($('select#tools option:selected').val() !== 'div') return;
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.y = ev.pageY + window.pageYOffset;
mouse.x = ev.pageX + window.pageXOffset;
} else if (ev.clientX) { //IE
mouse.y = ev.clientY + document.body.scrollTop;
mouse.x = ev.clientX + document.body.scrollLeft;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
// Mouse Event Handlers
canvas.onmousemove = function(e) {
if ($('select#tools option:selected').val() !== 'div') return;
setMousePosition();
if (element !== null) {
element.style.position = $('select#position option:selected').val();
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.margin = $('#elm-margin').val();
element.style.padding = $('#elm-padding').val();
element.style.color = $('#elm-color').val();
element.style.border = $('#elm-border').val();
element.style.borderRadius = $('#elm-border-radius').val();
element.style.MozBorderRadius = $('#elm-border-radius').val();
element.style.background = $('#elm-bgcolor').val();
element.style.boxShadow = $('#elm-boxshadow').val();
element.style.textShadow = $('#elm-txtshadow').val();
element.style.overflow = 'auto';
$('#elm-top').val(element.style.top);
$('#elm-left').val(element.style.left);
$('#elm-width').val(element.style.width);
$('#elm-height').val(element.style.height);
}
};
canvas.onmousedown = function(e) {
if ($('select#tools option:selected').val() !== 'div') return;
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
} else {
console.log("begun.");
mouse.startY = mouse.y;
mouse.startX = mouse.x;
element = document.createElement('div');
element.className = 'rect';
element.style.top = mouse.y + 'px';
element.style.left = mouse.x + 'px';
canvas.appendChild(element);
element.appendChild(document.createTextNode($('#insidediv').val()));
canvas.style.cursor = "crosshair";
}
};
canvas.onmouseup = function(e) {
if ($('select#tools option:selected').val() !== 'div') return;
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
code.val(preview.html());
coder.val(preview.html());
$('.select-tool').trigger('click');
};

Using jQuery, you can get the value of any css property using $(element).css('property-name');
Here's a quick example using that, as well as using .offset().top and .offset().left as alternative for getting those values. (These are also jQuery methods):
http://jsfiddle.net/sx8B3/

Related

Position DIV at cursor but within viewable area

I'm using the showDiv function below to display a DIV popup menu at the cursor position but I can't figure out how to tweak it so that the menu doesn't disappear off the bottom or right-hand edge of the viewable area, is it possible to compensate for this before displaying the DIV?
var posx;
var posy;
function getMouse(e){
posx = 0;
posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY){
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY){
posx = e.clientX;
posy = e.clientY;
}
}
function showDiv(id){
var obj = document.getElementById(id);
obj.style.left=posx+'px';
obj.style.top=posy+'px';
obj.style.display='block';
}
...
<body onMouseMove="getMouse(event)">
function showDiv(id){
var obj = document.getElementById(id),
screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0) - (obj.clientWidth || obj.offsetWidth),
screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0) - (obj.clientHeight || obj.offsetHeight);
obj.style.left = Math.min(posx, screenWidth) + 'px';
obj.style.top = Math.min(posy, screenHeight) + 'px';
obj.style.display = 'block';
}
This should keep the div within the view-able area.
You just check to see if the width plus the position etc are more or less than the values of the view-able area.
We also add on the scroll left and scroll top values so our calculations don't mistakenly think it's visible; you can remove that if it's not needed in your case though.
function showDiv(id, posX, posY) {
var obj = document.getElementById(id),
objWidth = obj.offsetWidth,
objHeight = obj.offsetHeight,
docX = window.pageXOffset || document.documentElement.scrollLeft,
docY = window.pageYOffset || document.documentElement.scrollTop,
winWidth = document.documentElement.clientWidth,
winHeight = document.documentElement.clientHeight;
posX += docX;
posY += docY;
if (posX < docX) {
posX = docX;
} else if (posX + objWidth > winWidth + docX) {
posX = docX + (winWidth - objWidth);
}
if (posY < docY) {
posY = docY;
} else if (posY + objHeight > winHeight + docY) {
posY = docY + (winHeight - objHeight);
}
obj.style.top = posY + 'px';
obj.style.left = posX + 'px';
obj.style.display = 'block';
}

Capture user input on HTML canvas/Javascript and vice versa

I am trying to draw a rectangle in HTML5 canvas based on user input. I am also trying to do the opposite. If a user draws a rectangle in the canvas, the width and height values are dropped into the form. Please see my jsfiddle.
http://jsfiddle.net/hbrennan72/FyTx5/
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var rect = {};
//var drag = false;
function getarea()
{
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var perim = wid * 2 + hgt * 2;
if (wid =="") {
document.getElementById("errors").innerHTML = "The value for the width is blank.";
document.getElementById('wid').focus();
}
else if (hgt == "") {
document.getElementById("errors").innerHTML = "The value for the height is blank.";
document.getElementById("hgt").focus();
}
else if (isNaN (wid)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the width.";
document.getElementById('wid').focus();
}
else if (isNaN (hgt)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the height.";
document.getElementById("hgt").focus();
}
else if (wid <= 0) {
document.getElementById("errors").innerHTML = "The width is less than or equal to zero.";
document.getElementById('wid').focus();
}
else if (hgt <= 0) {
document.getElementById("errors").innerHTML = "The height is less than or equal to zero.";
document.getElementById("hgt").focus();
}
else if (wid > 500) {
document.getElementById("errors").innerHTML = "The width is greater than 500.";
document.getElementById('wid').focus();
}
else if (hgt > 500) {
document.getElementById("errors").innerHTML = "The height is greater than 500.";
document.getElementById("hgt").focus();
}
else {
window.document.getElementById("area").innerHTML = area;
window.document.getElementById("perim").innerHTML = perim;
document.getElementById("errors").innerHTML = "Please see results listed above.";
}
}
function updateform (){
"use strict"
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
draw();
}
function mouseDown(e)
{
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
canvas.style.cursor="crosshair";
drag = true;
}
function mouseUp () {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.wid = (e.pageX - this.offsetLeft) - rect.startX;
rect.hgt = (e.pageY - this.offsetTop) - rect.startY ;
context.clearRect(0,0,canvas.width,canvas.height);
draw();
}
}
function init() {
canvas.addEventListener("mousedown", mouseDown, false);
canvas.addEventListener("mouseup", mouseUp, false);
canvas.addEventListener("mousemove", mouseMove, false);
}
init();
function drawform() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
}
function draw (){
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(rect.startX, rect.startY, rect.wid, rect.hgt);
context.fillStyle = "#378E37"; //green color
}
draw();
I have tried to do it in this way.It is working fine.The code is
$("#smt").click(function(){
var canvasel=' <canvas id="myCanvas" width="400" height="400"></canvas>'
$("#canvas").append(canvasel)
var w=$("#wid").val();
var h=$("#hgt").val();
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,w,h);
ctx.stroke();
})
$("#clr").click(function(){
$("#canvas").empty();
$("#wid").val('');
$("#hgt").val('');
})
initDraw(document.getElementById('canvas'));
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition();
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
var width=$(".rectangle").width();
var height=$(".rectangle").height();
$("#wid").val(width);
$("#hgt").val(height)
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
SEE DEMO HERE
NOTE:Its not working in Mozilla. I am trying to fix it.Check in Chrome

Simple drag and drop code

Im struggling with seemingly a simple javascript exercise, writing a vanilla drag and drop. I think Im making a mistake with my 'addeventlisteners', here is the code:
var ele = document.getElementsByClassName ("target")[0];
var stateMouseDown = false;
//ele.onmousedown = eleMouseDown;
ele.addEventListener ("onmousedown" , eleMouseDown , false);
function eleMouseDown () {
stateMouseDown = true;
document.addEventListener ("onmousemove" , eleMouseMove , false);
}
function eleMouseMove (ev) {
do {
var pX = ev.pageX;
var pY = ev.pageY;
ele.style.left = pX + "px";
ele.style.top = pY + "px";
document.addEventListener ("onmouseup" , eleMouseUp , false);
} while (stateMouseDown === true);
}
function eleMouseUp () {
stateMouseDown = false;
document.removeEventListener ("onmousemove" , eleMouseMove , false);
document.removeEventListener ("onmouseup" , eleMouseUp , false);
}
Here's a jsfiddle with it working: http://jsfiddle.net/fpb7j/1/
There were 2 main issues, first being the use of onmousedown, onmousemove and onmouseup. I believe those are only to be used with attached events:
document.body.attachEvent('onmousemove',drag);
while mousedown, mousemove and mouseup are for event listeners:
document.body.addEventListener('mousemove',drag);
The second issue was the do-while loop in the move event function. That function's being called every time the mouse moves a pixel, so the loop isn't needed:
var ele = document.getElementsByClassName ("target")[0];
ele.addEventListener ("mousedown" , eleMouseDown , false);
function eleMouseDown () {
stateMouseDown = true;
document.addEventListener ("mousemove" , eleMouseMove , false);
}
function eleMouseMove (ev) {
var pX = ev.pageX;
var pY = ev.pageY;
ele.style.left = pX + "px";
ele.style.top = pY + "px";
document.addEventListener ("mouseup" , eleMouseUp , false);
}
function eleMouseUp () {
document.removeEventListener ("mousemove" , eleMouseMove , false);
document.removeEventListener ("mouseup" , eleMouseUp , false);
}
By the way, I had to make the target's position absolute for it to work.
you can try this fiddle too, http://jsfiddle.net/dennisbot/4AH5Z/
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>titulo de mi pagina</title>
<style>
#target {
width: 100px;
height: 100px;
background-color: #ffc;
border: 2px solid blue;
position: absolute;
}
</style>
<script>
window.onload = function() {
var el = document.getElementById('target');
var mover = false, x, y, posx, posy, first = true;
el.onmousedown = function() {
mover = true;
};
el.onmouseup = function() {
mover = false;
first = true;
};
el.onmousemove = function(e) {
if (mover) {
if (first) {
x = e.offsetX;
y = e.offsetY;
first = false;
}
posx = e.pageX - x;
posy = e.pageY - y;
this.style.left = posx + 'px';
this.style.top = posy + 'px';
}
};
}
</script>
</head>
<body>
<div id="target" style="left: 10px; top:20px"></div>
</body>
</html>
I've just made a simple drag.
It's a one liner usage, and it handles things like the offset of the mouse to the top left corner of the element, onDrag/onStop callbacks, and SVG elements dragging
Here is the code.
// simple drag
function sdrag(onDrag, onStop) {
var startX = 0;
var startY = 0;
var el = this;
var dragging = false;
function move(e) {
el.style.left = (e.pageX - startX ) + 'px';
el.style.top = (e.pageY - startY ) + 'px';
onDrag && onDrag(el, e.pageX, startX, e.pageY, startY);
}
function startDragging(e) {
if (e.currentTarget instanceof HTMLElement || e.currentTarget instanceof SVGElement) {
dragging = true;
var left = el.style.left ? parseInt(el.style.left) : 0;
var top = el.style.top ? parseInt(el.style.top) : 0;
startX = e.pageX - left;
startY = e.pageY - top;
window.addEventListener('mousemove', move);
}
else {
throw new Error("Your target must be an html element");
}
}
this.addEventListener('mousedown', startDragging);
window.addEventListener('mouseup', function (e) {
if (true === dragging) {
dragging = false;
window.removeEventListener('mousemove', move);
onStop && onStop(el, e.pageX, startX, e.pageY, startY);
}
});
}
Element.prototype.sdrag = sdrag;
and to use it:
document.getElementById('my_target').sdrag();
You can also use onDrag and onStop callbacks:
document.getElementById('my_target').sdrag(onDrag, onStop);
Check my repo here for more details:
https://github.com/lingtalfi/simpledrag
this is how I do it
var MOVE = {
startX: undefined,
startY: undefined,
item: null
};
function contentDiv(color, width, height) {
var result = document.createElement('div');
result.style.width = width + 'px';
result.style.height = height + 'px';
result.style.backgroundColor = color;
return result;
}
function movable(content) {
var outer = document.createElement('div');
var inner = document.createElement('div');
outer.style.position = 'relative';
inner.style.position = 'relative';
inner.style.cursor = 'move';
inner.style.zIndex = 1000;
outer.appendChild(inner);
inner.appendChild(content);
inner.addEventListener('mousedown', function(evt) {
MOVE.item = this;
MOVE.startX = evt.pageX;
MOVE.startY = evt.pageY;
})
return outer;
}
function bodyOnload() {
document.getElementById('td1').appendChild(movable(contentDiv('blue', 100, 100)));
document.getElementById('td2').appendChild(movable(contentDiv('red', 100, 100)));
document.addEventListener('mousemove', function(evt) {
if (!MOVE.item) return;
if (evt.which!==1){ return; }
var dx = evt.pageX - MOVE.startX;
var dy = evt.pageY - MOVE.startY;
MOVE.item.parentElement.style.left = dx + 'px';
MOVE.item.parentElement.style.top = dy + 'px';
});
document.addEventListener('mouseup', function(evt) {
if (!MOVE.item) return;
var dx = evt.pageX - MOVE.startX;
var dy = evt.pageY - MOVE.startY;
var sty = MOVE.item.style;
sty.left = (parseFloat(sty.left) || 0) + dx + 'px';
sty.top = (parseFloat(sty.top) || 0) + dy + 'px';
MOVE.item.parentElement.style.left = '';
MOVE.item.parentElement.style.top = '';
MOVE.item = null;
MOVE.startX = undefined;
MOVE.startY = undefined;
});
}
bodyOnload();
table {
user-select: none
}
<table>
<tr>
<td id='td1'></td>
<td id='td2'></td>
</tr>
</table>
While dragging, the left and right of the style of the parentElement of the dragged element are continuously updated. Then, on mouseup (='drop'), "the changes are committed", so to speak; we add the (horizontal and vertical) position changes (i.e., left and top) of the parent to the position of the element itself, and we clear left/top of the parent again. This way, we only need JavaScript variables for pageX, pageY (mouse position at drag start), while concerning the element position at drag start, we don't need JavaScript variables for that (just keeping that information in the DOM).
If you're dealing with SVG elements, you can use the same parent/child/commit technique. Just use two nested g, and use transform=translate(dx,dy) instead of style.left=dx, style.top=dy

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/

Slow down dragging speed?

I am using the following function to drag a div:
function enableDragging(ele, ell) {
var dragging = dragging || false,
x, y, Ox, Oy,
current;
enableDragging.z = enableDragging.z || 1;
var grabber = document.getElementById(ell);
grabber.onmousedown = function (ev) {
ev = ev || window.event;
var target = ev.target || ev.srcElement;
current = target.parentNode;
dragging = true;
x = ev.clientX + 2;
y = ev.clientY + 2;
Ox = current.offsetLeft;
Oy = current.offsetTop;
current.style.zIndex = ++enableDragging.z;
var viewportWidth = viewport().width;
var viewportHeight = viewport().height;
document.onmousemove = function (ev) {
ev = ev || window.event;
if (dragging == true) {
var Sx = parseFloat(ev.clientX) - x + Ox;
var Sy = parseFloat(ev.clientY) - y + Oy;
current.style.left = Math.min(Math.max(Sx, Math.min(viewport().width - Sx, 0)), viewportWidth - current.offsetWidth) + "px";
current.style.top = Math.min(Math.max(Sy, Math.min(viewport().height - Sy, 0)), viewportHeight - current.offsetHeight) + "px";
}
}
document.onselectstart = function () {
return false;
};
document.onmouseup = function (ev) {
ev = ev || window.event;
dragging && (dragging = false);
if (ev.preventDefault) {
ev.preventDefault();
}
}
document.body.style.MozUserSelect = "none";
document.body.style.cursor = "default";
return false;
};
}
function viewport() {
var e = window
, a = 'inner';
if ( !( 'innerWidth' in window ) ) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}
This is how i start the drag:
var ele = document.getElementById("snapifyWrapper");
enableDragging(ele, 'hndl');
Im trying to figure out how i can make the drag slower? Basically i want to slow down the speed at which the div is being dragged
In your document.onmousemove() function, maybe check that Sx and Sy are different enough from x and y before moving the current object?
So specify a threshold and compare with that prior to moving the object.
// need to have displacement of 10px before moving the object
var threshold = 10;
var getAbs = Math.abs; // local reference to Math.abs() function
document.onmousemove = function (ev) {
ev = ev || window.event;
if (dragging == true) {
var Sx = parseFloat(ev.clientX) - x + Ox;
var Sy = parseFloat(ev.clientY) - y + Oy;
if (getAbs(Sx) > threshold || getAabs(Sy) > threshold) {
// move it
current.style.left = Math.min(Math.max(Sx, Math.min(viewport().width - Sx, 0)), viewportWidth - current.offsetWidth) + "px";
current.style.top = Math.min(Math.max(Sy, Math.min(viewport().height - Sy, 0)), viewportHeight - current.offsetHeight) + "px";
}
}
}
You may also add a timer to specify how long before mousemove should record the coordinates.

Categories

Resources