Saving position for div after dragging - javascript

I have the following script, when dragging the gray handler (top left) div re-sizes but at release of the mouse div is being place in the wrong place (at left margin).
I need to fix it as would be the bottom right handler.
What could be the problem? It seems related with event.clientX which is set to 0.
NOTES: click on the div to activate the handlers.
http://jsfiddle.net/cx41otxp/
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#target {
background-color: lightgreen;
}
.selected {
border: 1px dashed red;
}
.handler {
position: absolute;
width: 10px;
height: 10px;
background-color: gray;
}
</style>
<script>
window.App = {
config: {
elm: 'target',
elmInnerContent: 'inner-content',
x: null,
y: null,
w: null,
h: null,
handlerSize: 10
},
start: function () {
this.addEventListeners();
},
addEventListeners: function () {
var elm = document.getElementById(this.config.elm);
elm.addEventListener('click', function () {
if (!elm.classList.contains('selected')) {
elm.classList.add('selected');
this.getDimensions();
this.createHandlers();
this.setPositionHandlers();
this.addEventListenersHandlers();
} else {
elm.classList.remove('selected');
this.removeHandlers();
}
}.bind(this));
},
removeHandlers: function () {
var elm = document.getElementById('handler-wrapper');
elm.parentElement.removeChild(elm);
},
getDimensions: function () {
var elm = document.getElementById(this.config.elm);
this.config.x = elm.offsetLeft;
this.config.y = elm.offsetTop;
this.config.w = elm.clientWidth;
this.config.h = elm.clientHeight;
},
createHandlers: function () {
var wrpHandlers = document.createElement('div'),
htmlHandlers = '<div id="tl" class="tl handler" draggable="true"> </div>';
htmlHandlers += '<div id="tr" class="tr handler" draggable="true"> </div>';
htmlHandlers += '<div id="bl" class="bl handler" draggable="true"> </div>';
htmlHandlers += '<div id="br" class="br handler" draggable="true"> </div>';
wrpHandlers.id = "handler-wrapper";
wrpHandlers.innerHTML = htmlHandlers;
var elm = document.getElementById(this.config.elm);
elm.appendChild(wrpHandlers);
},
setPositionHandlers: function () {
this.getDimensions();
var elmTl = document.getElementById('tl'),
elmTr = document.getElementById('tr'),
elmBl = document.getElementById('bl'),
elmBr = document.getElementById('br');
elmTl.style.top = this.config.handlerSize * -1 + 'px';
elmTl.style.left = this.config.handlerSize * -1 + 'px';
elmTr.style.top = this.config.handlerSize * -1 + 'px';
elmTr.style.left = this.config.w + 'px';
elmBl.style.top = this.config.h + 'px';
elmBl.style.left = this.config.handlerSize * -1 + 'px';
elmBr.style.top = this.config.h + 'px';
elmBr.style.left = this.config.w + 'px';
},
addEventListenersHandlers: function () {
var elmTl = document.getElementById('tl'),
elmTr = document.getElementById('tr'),
elmBl = document.getElementById('bl'),
elmBr = document.getElementById('br');
elmTl.addEventListener('drag', function (event) {
this.resize('tl', event);
}.bind(this));
elmTr.addEventListener('drag', function (event) {
this.resize('tr', event);
}.bind(this));
elmBl.addEventListener('drag', function (event) {
this.resize('bl', event);
}.bind(this));
elmBr.addEventListener('drag', function (event) {
this.resize('br', event);
}.bind(this));
},
resize: function (handler, event) {
var elm = document.getElementById(this.config.elm);
switch (handler) {
case 'tl':
var marginR = elm.offsetLeft + elm.clientWidth,
newW = marginR - event.clientX,
xPos = event.clientX;
elm.style.left = xPos + 'px';
elm.style.width = newW + 'px';
this.setPositionHandlers();
break;
case 'tr':
break;
case 'bl':
break;
case 'br':
var newW = event.clientX - this.config.x,
newH = event.clientY - this.config.y;
elm.style.width = newW + 'px';
elm.style.height = newH + 'px';
this.setPositionHandlers();
break;
}
},
};
</script>
<title></title>
</head>
<body onload="window.App.start();">
<div id="target" style="position: absolute; top: 100px; left: 100px; width: 100px; height: 100px;">
<div id="inner-content">
Some text here
</div>
</div>
</body>
</html>

In the resize function, case 'tl': you have to do the same thing for top & height, what you do for left & width.
marginT = elm.offsetTop + elm.clientHeight,
newH = marginT - event.clientY,
yPos = event.clientY;
and
elm.style.top = yPos + 'px';
elm.style.height = newH + 'px';
Edit: Sorry, I think misread something the first time.
FYI: your code is working fine in Safari, but in Chrome, I see your problem.
Edit2: I don't know what causes this. But if you just check xPos >= 0, you can work around it. I know it's an ugly hack, but this is the best I have. Fiddle updated.

Related

Make div follow cursor on button click, and stop following cursor and go back to starting position on (another) button click

var bx = document.getElementById("movingbox");
var takeMeBtn = document.getElementById('takeMeBtn');
var letGoBtn = document.getElementById('letGoBtn');
function mouseMov(e) {
bx.style.left = -50 + e.clientX + "px";
bx.style.top = -50 + e.clientY + "px";
bx.style.zIndex = -99;
}
takeMeBtn.clickToggle = function fn(e) {
bx.style.left = -50 + e.clientX + "px";
bx.style.top = -50 + e.clientY + "px";
bx.style.zIndex = -99;
}
letGoBtn.onclick = function() {
bx.style.position = "fixed";
bx.style.top = 50;
bx.style.left = 50;
}
Hey people!
I've been trying to get "movingbox" to move and follow the cursors positions, when I click the button "takeMeBtn".
But, it only places itself in the current position of the cursor, when the "takeMeBtn" is clicked, and then stays there.
I also want to make it go back to its starting position, or anyposition, when I click "letGoBtn", but I think I can manage that one on my own.
I do not want to use jQuery for this.
Superthankful for any help.
Your buttons need to activate a mousemove listener for whatever you want to track the mouse over, probably the document or window. Other than that, you were close. I used inline style, but obviously a separate css document is better outside of this narrow example.
var bx = document.getElementById("movingbox");
var takeMeBtn = document.getElementById('takeMeBtn');
var letGoBtn = document.getElementById('letGoBtn');
function mouseMov(e) {
bx.style.left = -50 + e.clientX + "px";
bx.style.top = -50 + e.clientY + "px";
}
takeMeBtn.onclick = function(e) {
document.addEventListener('mousemove', mouseMov)
}
letGoBtn.onclick = function() {
document.removeEventListener('mousemove', mouseMov)
bx.style.top = "";
bx.style.left = "";
}
<button id="takeMeBtn">click</button>
<button id="letGoBtn">unclick</button>
<div id="movingbox" style="width:30px; height:30px; border: 1px solid black; position:absolute;"></div>
You can do it like this.
HTML:
<button id="takeMeBtn">take me</button>
<button id="letGoBtn">let go</button>
<div id="movingbox"></div>
var bx = document.getElementById("movingbox");
var takeMeBtn = document.getElementById('takeMeBtn');
var letGoBtn = document.getElementById('letGoBtn');
CSS
div {
width: 50px;
height: 50px;
background: red;
position: absolute;
}
JS
// flag: div should/not move
let move = false;
// switch flag
takeMeBtn.addEventListener('click', event => {
move = true;
});
// reset flag and position
letGoBtn.addEventListener('click', event => {
move = false;
bx.style.top = 0;
bx.style.left = 0;
bx.style.zIndex = 0;
});
// change its position on each mousemove event if the flag is set to true
document.addEventListener('mousemove', event => {
if (move === true) {
bx.style.top = event.clientY + 'px';
bx.style.left = event.clientX + 'px';
bx.style.zIndex = -99;
}
});

How am I able to randomly set the position of the image in javascript

I am trying to make the smile.png image to appear in a random position within the specific <div>.
What I have done is to set the variable.style.top= top_position+'px' & variable.style.left = left_position+"px".
However, what I am getting so far are the images the are horizontally aligned and not randomly positioned. How am I able to do that?
var theLeftSide = document.getElementById("leftSide");
var randomY = Math.round(Math.random()) + 'px';
var randomX = Math.round(Math.random()) + 'px';
function generateFaces() {
for (numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
createElement(numberOfFaces);
}
}
number = 0;
function createElement() {
number++;
//creating the image on the leftside
var smiley = document.createElement('img');
smiley.src = "smile.png";
smiley.style.position = "absolute";
smiley.style.left = randomX;
smiley.style.top = randomY;
theLeftSide.appendChild(smiley);
}
#leftSide {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
position: absolute;
width: 500px;
height: 500px;
left: 500px;
border-left: 1px solid black;
}
<body id="smileyGuessingGame" onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
</body>
There are few syntax errors in your code. You can compare your code with the code provided below.
Also note toFixed returns a A string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place.
Try this:
var theLeftSide = document.getElementById("leftSide"),
top_position = parseInt(Math.random() * ($(document).width() - 500)),
left_position = parseInt(Math.random() * ($(document).width() - 500));
function generateFaces() {
for (var numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
createElement(numberOfFaces);
}
}
var number = 0;
function createElement() {
number++;
//creating the image on the leftside
var smiley = document.createElement('img');
smiley.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Smiley_head_happy.svg/2000px-Smiley_head_happy.svg.png";
smiley.style.position = 'absolute';
smiley.style.top = top_position + "px";
smiley.style.left = left_position + "px";
theLeftSide.appendChild(smiley);
top_position += 20;
left_position += 20;
}
#leftSide {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
position: absolute;
width: 500px;
height: 500px;
left: 500px;
border-left: 1px solid black;
}
img {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body id="smileyGuessingGame" onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
</body>
Fiddle here
I'd code this using jQuery and lodash. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/3z6wsnyf/2/
The html:
<h1>Matching Game</h1>
<p>Find the unique image</p>
<div class="game"></div>
And the code:
var game = function(options) {
var panes = 2,
game = $('.game'),
height = 500,
width = game.width() / panes - 20,
itemSize = 50,
faces = 5,
guesses = 5,
setupBoard = function() {
game
.empty();
_.times(panes, function(p) {
game
.append(
$('<div>')
.addClass('pane pane' + p)
.css('height', height + 'px')
.css('width', width + 'px')
);
})
},
startGame = function() {
_.times(faces, function(i) {
_.times(panes, function(p) {
$('.pane' + p)
.append(
$('<img>')
.attr('src', 'http://lorempixel.com/200/20' + i)
.addClass('img-' + i)
.css('top', _.random(height - itemSize) + 'px')
.css('left', _.random(width - itemSize) + 'px')
);
})
});
$('.game img').click(function() {
guesses--;
alert('Nope! You\'ve got ' + guesses + ' guesses remaining.');
});
$('.pane' + _.random(panes - 1))
.append(
$('<img>')
.attr('src', 'http://lorempixel.com/200/20'+ (faces + 1))
.addClass('img-t')
.css('top', _.random(height - itemSize) + 'px')
.css('left', _.random(width - itemSize) + 'px')
.click(function() {
alert('You got it! Good job! You just cleared ' + faces + ' images! You\'ve got ' + guesses + ' guesses remaining.');
faces++;
setupBoard();
startGame();
})
);
$('.game img')
.css('height', itemSize + 'px')
.css('width', itemSize + 'px')
.css('-moz-border-radius', itemSize / 2 + 'px')
.css('-webkit-border-radius', itemSize / 2 + 'px')
.css('border-radius', itemSize / 2 + 'px')
.css('-khtml-border-radius', itemSize / 2 + 'px')
};
setupBoard();
startGame();
};
game();
Maybe something like this could work:
function generateRandom(min, max) {
var num = Math.random() * (max - min) + min;
return Math.floor(num);
}
var width,
height,
img;
width = $( '#leftSide' ).width();
height = $( '#leftSide' ).height();
img = $('<img id="smiley">');
img.attr('src', 'http://vignette2.wikia.nocookie.net/robocraft/images/2/26/Smile.png');
img.css('top',generateRandom(0,height));
img.css('left',generateRandom(0,width));
img.appendTo('#leftSide');
demo: http://codepen.io/anon/pen/PZZrzz

Click And Drag function in javascript

I'm trying to create my own click and drag function in JavaScript without the use of jquery. I know that jquery is easy to implement, but I prefer my own code. What I have, as i click the div, then move the mouse, the div moves to the same spot and doesn't implement a "dragging" look to it. I'm not sure why this is. I want my outcome to be able to move the div over the image that way I can "crop" the image based on the div, etc. My code is:
index.js
function _(element) {
return document.getElementById(element);
}
index.css
body {
background-color: rgb(33, 66, 99);
margin: 0px;
padding: 0px;
}
img {
position:absolute;
}
.selection {
width: 200px;
height: 200px;
background-color: rgb(255,255,255);
position: absolute;
}
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8"/>
<title>Image Cropping</title>
<link rel = "stylesheet" href = "index.css"/>
<script src = "index.js"></script>
</head>
<body>
<div class = "image">
<img src = "model.jpg" alt = "Model" id = "theImage"/>
<div class = "selection" id = "selection"/>
</div>
<script>
_("theImage").ondragstart = function() { return false; };
var m = _("selection");
m.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
function mouseUp() {
window.removeEventListener("mousemove", move, true);
}
function mouseDown(e) {
window.addEventListener("mousemove", move, true);
}
function move(e) {
var x = m.style.left;
var y = m.style.top;
var mouseX = e.clientX;
var mouseY = e.clientY;
m.style.top += (mouseX - x) + "px";
m.style.left += (mouseY - y) + "px";
// Also tried: m.style.top = (mouseX - x) + "px";
// And : m.style.left = (mouseY - y) + "px";
}
</script>
</body>
</html>
To add the "dragging look to it", you can:
change the cursor (cursor: move;)
keep the cursor's offset relative to the mouse
For the second one, I reused a function I created for one of my projects, for which I implemented drag and drop for mobile, not wanting to use a big library:
/*
* Returns the given element's offset relative to the document.
*/
function realOffset(elem) {
var top = 0, left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop, 10);
left = left + parseInt(elem.offsetLeft, 10);
elem = elem.offsetParent;
}
return { top: top, left: left };
}
Using this function, the math becomes simple:
m.style.left = (mouseX - offset.left) + "px";
m.style.top = (mouseY - offset.top) + "px";
Full demo
_("theImage").ondragstart = function () { return false; };
var m = _("selection"), offset;
m.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
function mouseUp() { window.removeEventListener("mousemove", move, true); }
function mouseDown(e) {
// SAVE THE OFFSET HERE
offset = {
left: e.pageX - realOffset(m).left,
top: e.pageY - realOffset(m).top
};
window.addEventListener("mousemove", move, true);
}
function move(e) {
// REUSE THE OFFSET HERE
m.style.left = (e.pageX - offset.left) + "px";
m.style.top = (e.pageY - offset.top) + "px";
}
/*
* Returns the given element's offset relative to the document.
*/
function realOffset(elem) {
var top = 0, left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop, 10);
left = left + parseInt(elem.offsetLeft, 10);
elem = elem.offsetParent;
}
return { top: top, left: left };
}
function _(element) { return document.getElementById(element); }
body {
background-color: rgb(33, 66, 99);
margin: 0px;
padding: 0px;
}
img {
position:absolute;
}
.selection {
width: 200px;
height: 200px;
background-color: rgba(255,255,255,.5);
position: absolute;
cursor: move;
}
<div class="image">
<img src="http://i.imgur.com/vxkljMP.jpg" alt="Model" id="theImage" />
<div class="selection" id="selection"></div>
</div>

Dragging elements on a scaled div

I've tried using jquery's built in draggable and I've tried using custom drag functions with no avail. Both have their respected issues and I will try to highlight both of them.
Basically, I am trying to allow the dragging of an element that is on a scaled div container. The following methods work okay on a scaled element that is less than around 2. But if you go any higher than that, we see some issues.
Any help would be appreciated. Thank you for your time.
HTML
<div id="container">
<div id="dragme">Hi</div>
</div>
Method 1 (Jquery draggable function)
I've tried the jquery draggable function as you can see in this jsfiddle example.
The problems I found in this example are the following:
Biggest concern: The droppable container does not change when it is scaled up. So if the element is being dragged over part of the scaled container that isn't a part of it's original size, it will fail.
When you click to drag a div, it teleports a little bit away from the mouse and is not a seamless drag.
JS
var percent = 2.5;
$("#dragme").draggable({
zIndex: 3000,
appendTo: 'body',
helper: function (e, ui) {
var draggable_element = $(this),
width = draggable_element.css('width'),
height = draggable_element.css('height'),
text = draggable_element.text(),
fontsize = draggable_element.css('font-size'),
textalign = draggable_element.css('font-size');
return $('<div id="' + draggable_element.id + '" name="' + draggable_element.attr('name') + '" class="text">' + text + '</div>').css({
'position': 'absolute',
'text-align': textalign,
'background-color': "red",
'font-size': fontsize,
'line-height': height,
'width': width,
'height': height,
'transform': 'scale(' + percent + ')',
'-moz-transform': 'scale(' + percent + ')',
'-webkit-transform': 'scale(' + percent + ')',
'-ms-transform': 'scale(' + percent + ')'
});
},
start: function (e, ui) {
$(this).hide();
},
stop: function (e, ui) {
$(this).show();
}
});
$("#container").droppable({
drop: function (event, ui) {
var formBg = $(this),
x = ui.offset.left,
y = ui.offset.top,
drag_type = ui.draggable.attr('id');
var element_top = (y - formBg.offset().top - $(ui.draggable).height() * (percent - 1) / 2) / percent,
element_left = (x - formBg.offset().left - $(ui.draggable).width() * (percent - 1) / 2) / percent;
$(ui.draggable).css({
'top': element_top,
'left': element_left
});
}
});
Method 2 - Custom drag function
I've tried using a custom drag function but it unusable after around a 2 scale.
jsfiddle on a scale(2) - Looks like the draggable div is having a seizure.
jsfiddle on a scale(2.5) - The draggable div flys away when you try to drag it.
JS
(function ($) {
$.fn.drags = function (opt) {
opt = $.extend({
handle: "",
cursor: "move"
}, opt);
if (opt.handle === "") {
var $el = this;
} else {
var $parent = this;
var $el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown", function (e) {
if (opt.handle === "") {
var $drag = $(this).addClass('draggable');
} else {
$(this).addClass('active-handle')
var $drag = $parent.addClass('draggable');
}
var
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
follow = function (e) {
$drag.offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
})
};
$(window).on("mousemove", follow).on("mouseup", function () {
$drag.removeClass('draggable');
$(window).off("mousemove", follow);
});
e.preventDefault(); // disable selection
}).on("mouseup", function () {
if (opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle');
$parent.removeClass('draggable');
}
});
}
})(jQuery);
$("#dragme").drags({}, function (e) {});
Here are a few of my findings to make sure dragging on a scaled container works for method one. The only caveat is to make sure you have var percent as the scaled percentage declared before any of these actions happen.
First, use this code at the top of your javascript. This wil help making sure that the droppable area works with a sacled container.
$.ui.ddmanager.prepareOffsets = function( t, event ) { var i, j, m = $.ui.ddmanager.droppables[ t.options.scope ] || [], type = event ? event.type : null, list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack(); droppablesLoop: for ( i = 0; i < m.length; i++ ) { if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) { continue; } for ( j = 0; j < list.length; j++ ) { if ( list[ j ] === m[ i ].element[ 0 ] ) { m[ i ].proportions().height = 0; continue droppablesLoop; }  } m[ i ].visible = m[ i ].element.css( "display" ) !== "none"; if ( !m[ i ].visible ) { continue; } if ( type === "mousedown" ) { m[ i ]._activate.call( m[ i ], event ); } m[ i ].offset = m[ i ].element.offset(); m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth * percent, height: m[ i ].element[ 0 ].offsetHeight * percent }); } };
Here are a few functions that are necessary to fix the drag so it works on a scaled container.
function dragFix(event, ui) { var changeLeft = ui.position.left - ui.originalPosition.left, newLeft = ui.originalPosition.left + changeLeft / percent, changeTop = ui.position.top - ui.originalPosition.top, newTop = ui.originalPosition.top + changeTop / percent; ui.position.left = newLeft; ui.position.top = newTop; }
function startFix(event, ui) { ui.position.left = 0; ui.position.top = 0;  var element = $(this); }
You will want this if you want to enable the element to be resizable on a scaled container.
function resizeFix(event, ui) { var changeWidth = ui.size.width - ui.originalSize.width, newWidth = ui.originalSize.width + changeWidth / percent, changeHeight = ui.size.height - ui.originalSize.height, newHeight = ui.originalSize.height + changeHeight / percent;  ui.size.width = newWidth; ui.size.height = newHeight; }
To make an element draggable, I use the following function.
$("ELEMENT").resizable({ minWidth: - ($(this).width()) * 10, minHeight: - ($(this).height()) * 10, resize: resizeFix, start: startFix });
$("ELEMENT").draggable({ cursor: "move", start: startFix, drag: dragFix }); }
A similar problem is mentioned here: jquery - css "transform:scale" affects '.offset()' of jquery
It seems the problem arises from the fact that jQuery fails to return exact size for scaled elements and therefore failing setting right offset values to the element.
To solve this, he is suggesting first setting scale to 1 and setting offset and then again resetting scale value.
But this alone does not solve the problem here. Since mouse position is taken while it is scaled, position values should also be divided by scale value.
Here is an edited version of code:
var scl = 2.5;
var
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top/scl + drg_h - e.pageY/scl,
pos_x = $drag.offset().left/scl + drg_w - e.pageX/scl;
follow = function(e) {
var size = {
top:e.pageY/scl + pos_y - drg_h+scl*2,
left:e.pageX/scl + pos_x - drg_w+scl*2
};
$drag.parent().css("transform","scale(1)");
$drag.offset(size);
$drag.parent().css("transform","scale("+scl+")");
};
Note: I only replaced scale value for transform tag, since I am using chrome. You can also replace all instances or instead you can use a different class with 1 scale value.
JSFiddle is also here.
Here is an example of simple drag with scaling, however, in prue dom.
<style>
#dragme {
position:absolute;
border:1px solid red;
background:pink;
left:10px;
top:20px;
width:100px;
height:200px;
}
#container {
transform: scale(2,2) translate(100px,100px);
position:relative;
border:1px solid green;
background:grey;
width:200px;
height:300px;
}
</style>
<body>
<div id="container">
<div id="dragme">Hi</div>
</div>
<script>
var dragme=document.getElementById("dragme");
var container=document.getElementById("container");
dragme.onmousedown=function Drag(e){
this.ini_X = this.offsetLeft-e.clientX/2;
this.ini_Y = this.offsetTop-e.clientY/2;
container.onmousemove = move;
container.onmouseup = release;
return false;
}
function move(e){
e.target.style.left = e.clientX/2 + e.target.ini_X + 'px';
e.target.style.top = e.clientY/2 + e.target.ini_Y + 'px';
}
function release(){
container.onmousemove=container.onmouseup=null;
}
</script>
</body>

mousedown div containment to parent(latest)

My inner div is suppose to move around with the mouse cursor on mousemove but i want it to stop at the if statement if it is dragging with the isDragging variable so it will drag smoothly but it seems to not stop any suggestion and help would be appreciated
update: jsFiddle
var yellow = $('#yellow');
var offset = yellow.offset();
var offsetWidth = offset.left + yellow.width();
var offsetHeight = offset.top + yellow.height();
var isDragging = false;
var red = $('#red');
$('#red').hide();
yellow.on('mousedown', function(event) {
$('#red').show();
});
yellow.on('mouseup', function(event) {
$('#red').hide();
});
yellow.on('mousemove', function (e) {
if(e.pageX > offset.left + ($(red).width() / 2) && e.pageX < offsetWidth - ($(red).width() / 2)
&& e.pageY > offset.top + ($(red).height() / 2) && e.pageY < offsetHeight - ($(red).height() / 2) && !isDragging ){
red.css("left", e.pageX - $(red).width() / 2 );
red.css("top", e.pageY - $(red).height() / 2);
}
$('#red').draggable(
{'containment':'#yellow',
start:function(event, ui) {
isDragging = true;
},
drag:function(event, ui) {
isDragging = true;
},stop:function(event, ui) {
isDragging = false;
}
});
});
<div id="yellow">
<div id="red"></div>
</div>
#yellow {
position: absolute;
width: 250px;
height: 250px;
background-color: Yellow;
}
#red {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
z-index: 100;
}
I can't say i am proud of this solution but it seems to get the stuff done:
http://jsfiddle.net/pPn3v/42/
var yellow = $('#yellow');
var offset = yellow.offset();
var offsetWidth = offset.left + yellow.width();
var offsetHeight = offset.top + yellow.height();
var red = $('#red');
yellow.on('mousemove', function (e) {
if(e.pageX+red.width() < offsetWidth
&& e.pageY+red.height() < offsetHeight){
red.css("left", e.pageX);
red.css("top", e.pageY);
}
});
red.on('mousemove', function (e) {
if(e.pageX+red.width() < offsetWidth
&& e.pageY+red.height() < offsetHeight){
red.css("left", e.pageX);
red.css("top", e.pageY);
}
});

Categories

Resources