Reputation: 3303
below code try to make img be draggable(regarding this), it works but I can't figure how to make if img move all wrap drag_wp
move together. http://jsfiddle.net/cAeKG/8/ any suggestion?
js
function enableDraggin(el){
var dragging = dragging || false, x, y, ox, oy, current;
el.onmousedown = function(e){
e.preventDefault();
current = e.target;
dragging = true;
x = e.clientX;
y = e.clientY;
ox = current.offsetLeft;
oy = current.offsetTop;
window.onmousemove = function(e) {
if (dragging == true) {
var sx = e.clientX - x + ox,
sy = e.clientY - y + oy;
current.style.left = sx + "px";
current.style.top = sy + "px";
return false;
}
};
window.onmouseup = function(e) {
dragging && (dragging = false);
};
};
};
var el = $('.drag_wp');
for(var i = 0; i < el.length; i++){
enableDragging(el[i]);
};
html & css
<div class="drag_wp">
<img src="..." class="drag_el">
<div></div>
....// other div
</div>
.drag_wp{
position: absolute;
width: auto;
height: auto;
background:red;
}
.drag_el{
position: absolute;
width: 200px;
height: auto;
}
Upvotes: 0
Views: 123
Reputation: 193261
I made some modifications to your code:
function enableDragging(el) {
var dragging = dragging || false,
x, y, ox, oy, current;
el.onmousedown = function (e) {
e.preventDefault();
current = e.target.parentNode; // <--- current should be wrapper, not image
dragging = true;
x = e.clientX;
y = e.clientY;
ox = current.offsetLeft;
oy = current.offsetTop;
window.onmousemove = function (e) {
if (dragging == true) {
var sx = e.clientX - x + ox,
sy = e.clientY - y + oy;
current.style.left = sx + "px";
current.style.top = sy + "px";
return false;
}
};
window.onmouseup = function (e) {
dragging && (dragging = false);
};
};
};
Upvotes: 1
Reputation: 12815
function enableDraggin(el){
var dragging = dragging || false, x, y, ox, oy, current;
el.onmousedown = function(e){
e.preventDefault();
current = e.target;
//just add this
if(!$(current).hasClass(".drag_wp"))
current = $(current).closest(".drag_wp")[0];
//just add this
dragging = true;
x = e.clientX;
y = e.clientY;
ox = current.offsetLeft;
oy = current.offsetTop;
window.onmousemove = function(e) {
if (dragging == true) {
var sx = e.clientX - x + ox,
sy = e.clientY - y + oy;
current.style.left = sx + "px";
current.style.top = sy + "px";
return false;
}
};
window.onmouseup = function(e) {
dragging && (dragging = false);
};
};
};
e.target
returns element that was clicked (image in most cases for your HTML). If it has no class .drag_wp
, just find closest parent with that class and use it as current.
Demo: http://jsfiddle.net/fTeXL/
Also, as you are already using jquery, you may find it better to use corresponding plugin from jQuery UI: http://jqueryui.com/draggable/
Upvotes: 1