Sébastien Gicquel Sébastien Gicquel - 3 months ago 12
Javascript Question

Drag multiple elements with jquery.event.drag

I want to drag multiple elements with the jQuery plugin jquery.event.drag

Here is a fiddle of the original demo :

Here is the link to the original demo :

On the demo, the user clicks on squares he wants to select and drag them.

But i want to do something simplest : Just click on the square "1" and move all the squares.

I've tried different things and the result is not good, see this fiddle :

http://jsfiddle.net/Vinyl/gVFCL/2/

Can you help me to that that ?

HTML code :

<div class="drag" style="left:20px;"></div>
<div class="drag" style="left:100px;"></div>
<div class="drag" style="left:180px;"></div>


CSS code

.drag {
position: absolute;
border: 1px solid #89B;
background: #BCE;
height: 58px;
width: 58px;
cursor: move;
top: 120px;
}
.selected {
background-color: #ECB;
border-color: #B98;
}


jQuery

jQuery(function($){
$('.drag')
.click(function(){
$( this ).toggleClass("selected");
})
.drag("init",function(){
if ( $( this ).is('.selected') )
return $('.selected');
})
.drag(function( ev, dd ){
$( this ).css({
top: dd.offsetY,
left: dd.offsetX
});
});
});


EDIT
The link given in Rajagopal's answer is ok.
I've also found this plugin MultiDraggable which is really easy to use : https://github.com/someshwara/MultiDraggable

Answer

You have to do something like this,

$('.drag').drag("init", function(ev, dd) {
    if (this.id == "test") {
        return $(".drag").addClass("selected");
    }
}).drag(function(ev, dd) {
    if (ev.target.id == "test") {
        $(this).css({
            top: dd.offsetY,
            left: dd.offsetX
        });
    }
});​

Here is the working sample. Hope, this one will help you.

EDIT:

You can simply use jquery-ui draggable plugin for this case. Take a look at this http://jqfaq.com/how-to-drag-the-multiple-elements-with-jquery-ui-draggable/. Hoep, this one will help you!

Comments