Friday, January 23, 2015

Add div element on click and make it draggable using jquery

In this tutorial, i will show you how to add an box,div or element in an certain area then after it has been inserted, we will make it draggable.

We will use jquery ui and we will use the jquery offset function to accomplish this task, first we will get the coordinates of the clicked area then add an box on that spot.

Preview of the whole function
    
$('#layoutSpace').click(function(e){    
    var offset = $(this).offset();  
    areaBox = 50;//to center the mouse point
    mouseX = (e.pageX - offset.left - areaBox );
    mouseY =  (e.pageY - offset.top - areaBox );   
    $('#layoutSpace').append('<div class="dbox" style="left:'+ mouseX +'px;top:'+ mouseY  +'px;"></div>');
    //run the draggable function
 runTheDrag(); 
});    

MainlayoutX = $('#layoutSpace').offset().left; //Get main layout of the mainContainer
MainlayoutY = $('#layoutSpace').offset().top; //Get main layout of the mainContainer

//function for draggable box
function runTheDrag(){
    $(".dbox").draggable({ 
        containment: '#layoutSpace',
        scroll: false,   
        drag: function(){
            var offset = $(this).offset(); 
            var left = offset.left - MainlayoutX;
            var top = offset.top - MainlayoutY;   
            
            $(".dbox .xAxis").val(left);
            $(".dbox .yAxis").val(top);      
        }
    });    
}

This code will will register the area that is clicked by the mouse and add an box on that spot

    var offset = $(this).offset();  
    areaBox = 50;//to center the mouse point
    mouseX = (e.pageX - offset.left - areaBox );
    mouseY =  (e.pageY - offset.top - areaBox );   
    $('#layoutSpace').append('<div class="dbox" style="left:'+ mouseX +'px;top:'+ mouseY  +'px;"></div>');
    //run the draggable function
    runTheDrag(); 
});  
runTheDrag() function is to make the box draggable on click using jquery ui
 runTheDrag();

 function runTheDrag(){
    $(".dbox").draggable({ 
        containment: '#layoutSpace',
        scroll: false,   
        drag: function(){
            var offset = $(this).offset(); 
            var left = offset.left - MainlayoutX;
            var top = offset.top - MainlayoutY;   
            
            $(".dbox .xAxis").val(left);
            $(".dbox .yAxis").val(top);      
        }
    });    
} 

As you notice, we inserted the runTheDrag() function on to the click function
The reason is we need to rerun the jquery code on click to register the draggable function again on the newly added box.

Live Demo

No comments:

Post a Comment