Drag multiple items using jquery.event.drag

I want to drag multiple items using jQuery jquery.event.drag plugin

Here is the script for the original demo :

Here is the link to the original demo :

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

But I want to do something simple: just click on the square "1" and move all the squares.

I tried different things and the result is not very good, see this script:

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

Can you help me with this?

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 provided in Rajagopal’s answer is in order. I also found this MultiDraggable plugin that is very easy to use: https://github.com/someshwara/MultiDraggable

+4
source share
4 answers

You should 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 an example. Hope this one helps you.

EDIT:

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

+2
source
 jQuery(function($) { $('.drag').drag("init", function() { if ($(this).is('#test')){ return $('.selected'); } }).drag(function(ev, dd) { $( this ).css({ top: dd.offsetY, left: dd.offsetX }); }); }); 

Demo http://jsfiddle.net/gVFCL/3/

+2
source

My switching of several mods and multi select:

http://jsfiddle.net/F4AwY/

 $('.drag').drag("init", function() { return $('.selected'); }).drag(function(ev, dd) { $( this ).css({ top: dd.offsetY, left: dd.offsetX }); }); $('div[class*="drag"]').click(function(){ $(this).toggleClass("selected"); }) 
+2
source

In the original jsfiddle change

 .click(function(){ $(this).toggleClass("selected"); }) 

to

 .click(function(){ $('.drag').toggleClass("selected"); }) 
+1
source

All Articles