Skip to content Skip to sidebar Skip to footer

How To Make Two Divs Draggable?

Say I have Div1 and Div2. I want to make that when a user is dragging around Div1, Div2 should also drag along. Any ideas how do I make it? Here's what I got so far... $(document).

Solution 1:

have a look at http://docs.jquery.com/UI/Draggable#event-drag to see how to bind to a draggable event. Bind the draggable event of div1 to a function that changes the coordinates of div2

Cheers.

Solution 2:

Regarding your edit I've made some changes that can be viewed here http://jsfiddle.net/9FrXr/2/

You weren't closing the "drag" bind and instead of event.offsetY and event.offsetX I've used ui.offset.top and ui.offset.x. The drag bind has also been moved into the document.ready function.

$("#apDiv1").bind( "drag", function(event, ui) {
    div.css({ top: ui.offset.top + 52, left: ui.offset.left });
});

Solution 3:

// JavaScript Document
//This is an easy draggable javascript frameworkt
//There is no license for it so you can modify it how ever you like
//Coding started: 2011-05-28and finished 2011-05-09
//The code can contain bugs. I only use an array to store the ID:s of the draggables 

//Create an array for the draggers// I am not using an class because it is not nesesery for this easy thing
/////////////////////////////////////////////////////////////////////////////////////////////////////////
var Elements=new Array('draggable2','draggable3','draggable4','draggable5','draggable6','draggable7','draggable8','draggable9','draggable10');
//Set ID wher to do select disabeled
var textDisabling="body";
//Set drag TAG exeption//
var dragException=new Array('input','SPAN');
//////////////////////////////////////Start the framework 
document.onmousemove=drag;
document.onmousedown=mouseDown; 
document.onmouseup=mouseUp; 
var parent;
//Offset vars//     
var offsetY,offsetX;    
//Setup the timeout event holder here// 
var timeout=null;       
//Set a var that will hold the dragged object// 
var ObjectDrag;
    //Set boolean vars to elerate// 
var clickStage=true;    
var XPos, YPos;//<--Setting up the position vars//  

//////////////////////////////////////
//Get the browser name for your own needs//
//////////////////////////////////////      

function getBrowserName(){  

    var Navigator=navigator.userAgent;      

    if(Navigator.indexOf("MSIE")>=0){           

        Navigator="MSIE";           

    }else if(Navigator.indexOf("Netscape")>=0){             

        Navigator="Netscape";           

    }else if(Navigator.indexOf("Firefox")>=0){          

        Navigator="Firefox";            

    }else if(Navigator.indexOf("Opera")>=0){            

        Navigator="Opera";          

    }else if(Navigator.indexOf("Safari")>=0){           

        Navigator="Safari";         

    }else{      

        Navigator="NULL";       

    }//IF       

    return Navigator;       

}//Function 
//END// 
/////////////////////////////////////
//Get browser version to your neads//
/////////////////////////////////////   
function getBrowserVersion(){       

    var browserName=getBrowserName(),       

        findIndex,          

        browserVersion;         

        browserVersion=navigator.userAgent;         

        findIndex=browserVersion.indexOf(browserName) + browserName.length+1;           

        browserVersion=parseFloat(browserVersion.substr(findIndex,findIndex + 3));      

    return browserVersion;

}//Function 
//END// 
function getMousePos(event){        

    var event=event || window.event;
    //Get the position of the mouse with an offset of the top page
    //////////////////////////////////////////////////////////////

    if(event.pageX && event.pageY){ 

        //We get the mouse position in newer browsers//

        XPos=event.pageX;

        YPos=event.pageY;       

    }else{

        //We gat the same value as abow, but this is for older browsers//
        XPos=event.clientX + document.body.scrollLeft - document.body.clientLeft;           

        YPos=event.clientY + document.body.scrollTop  - document.body.clientTop;            
    }

    //This is only for debugging the mouse position//
    document.getElementById('X').value=XPos;/////////

    document.getElementById('Y').value=YPos;/////////

    return {XPos:XPos, YPos:YPos};      

}
//Function for disabling text selections//
function disableTextSelection(event){   

    var event=event || window.event;

    var object;

    if(getBrowserName() != "MSIE"){object=event.target;}else{object=event.srcElement;}

    if (typeof document.getElementById(textDisabling).onselectstart!="undefined"){ //IE route

        document.getElementById(textDisabling).onselectstart=function(){return false}

        object.onselectstart=function(){return false}

    }else if (typeof document.getElementById(textDisabling).style.MozUserSelect!="undefined"){ //Firefox route

        document.getElementById(textDisabling).style.MozUserSelect="none"

        object.style.MozUserSelect="none"


    }else{ //All other route (ie: Opera)

        document.getElementById(textDisabling).onmousedown=function(){return false}

        object.onmousestart=function(){return false}

    }           

}
//Allow text selection funtion. Call this when you do muse up//
function allowTextSelection(){

if (typeof document.getElementById(textDisabling).onselectstart!="undefined"){ //IE route

        document.getElementById(textDisabling).onselectstart=function(){return true}

        ObjectDrag.onselectstart=function(){return true}

    }else if (typeof document.getElementById(textDisabling).style.MozUserSelect!="undefined"){ //Firefox route

        document.getElementById(textDisabling).style.MozUserSelect="text"

        ObjectDrag.style.MozUserSelect="text"

    }else{ //All other route (ie: Opera)

        document.getElementById(textDisabling).onmousedown=function(){return true}

        ObjectDrag.onmousestart=function(){return true}
    }
}   

//Setup the global function that we will start from//   

function drag(event){       

    var mousePos=getMousePos(event);        

}

//Make an exception function //

function exception(event){  

    if(getBrowserName() != "MSIE"){     

        for(items in dragException){if(event.target.nodeName == dragException[items].toUpperCase())return {contin:false};}      

    }else{

        for(items in dragException){if(event.srcElement.nodeName == dragException[items].toUpperCase())return {contin:false};}      

    }

        return true;                

}

//This function checks if you are pulling the click inside the element

function isInside(event){

    var event=event || window.event;

    var object;

    if(getBrowserName() != "MSIE"){object=event.target;}else{object=event.srcElement;}

    if(object.nodeName=="HTML")return false;

    parent=object;      

    var i,l=0;      

    for(i=0;i<=l;i++){          

        if(parent.nodeName != "BODY"){          

            for(items in Elements){             

                if(Elements[items] == parent.id){                   

                    return {contin:true, id:parent};                    

                }                   

            }                           

            parent=parent.parentNode;               

            l++;            

        }else{              

            return false;               

        }

    }               

}



//Here we get the offset position so the element will follow the mouse where you

//did (mouseDown) event. If we noe capturing the offset, the element will lie line to line with the

//mouse. NO OFFSET  

function offsetObject(YPos,XPos){               

    offsetY=YPos-ObjectDrag.offsetTop;      

    offsetX=XPos-ObjectDrag.offsetLeft;     

    return false;               

}   

//Set the objects on a good z-index//   

function setZIndex(event){  

    var event=event || window.event;    

    var object;

    if(getBrowserName() != "MSIE"){object=event.target;}else{object=event.srcElement;}

    for(items in Elements){         

        document.getElementById(Elements[items]).style.zIndex="1";                      

    }           

    object.style.zIndex="20";   

}   

//Capture mouse down//

function mouseDown(event){

    var event=event || window.event;        

    /*if(getBrowserName() != "MSIE"){   */  

        timeout=null;               

        clickStage=true;            

        //Store the event if it´s not null and can be dragged//                     

            var inside=isInside(event);                         

            if(inside.contin == true && exception(event) == true){  

                /*Function that disables the text selection on drag*/

                disableTextSelection(event);                                

                ObjectDrag=inside.id;                                       

                offsetObject(YPos,XPos);                    

                //Set the z-indexes//

                setZIndex(event);                   

                moveObject();

            }           

        /*}else{                            

            alert("Browser is not suported");               

        }*/ 

    }

//Start moving the object//

function moveObject(){       

    //Stor the mouse event in this var//    

    if(clickStage == true)timeout=setTimeout(moveObject,0);     

    //Change it back to true if the mouseUp event has not trigged//     

    clickStage=true;        

    //Store the event if it´s not null and can be dragged//         

    if(clickStage==true){           

        //This is the place where we set the position of the element        

        document.getElementById(ObjectDrag.id).style.left=XPos-offsetX+"px";            

        document.getElementById(ObjectDrag.id).style.top=YPos-offsetY+"px";                             

    }

}



//Capture mouse up//

function mouseUp(event){

    var event=event || window.event;            

        if(exception(event) == true ){

        allowTextSelection();           

        timeout=null;           

        clickStage=false;       

        }

}

Solution 4:

Thanks again, got it fully working on the webpage. You can see it in action by moving the menu around at www[dot]skyeye[dot]cc .

<script>
    $(function() {
    $("#apDiv3").draggable();

    $("#apDiv3").bind("drag", function(event, masterdrag) {
        $("#apDiv5").css({ top: masterdrag.offset.top, left: masterdrag.offset.left-20 });
    });
});

  </script>

Post a Comment for "How To Make Two Divs Draggable?"