Search code examples
javascriptjqueryhtmldrag-and-dropdraggable

Drag & Drop with Jquery


There is my code:

<!doctype html>
<html lang="en">
<head>
    <title> Mrb. :) </title>
    <style>
        h1{
            text-align: center;
        }
        #finishImage { 
            width:64px; 
            height:64px; 
            }
        #palette{
            position: absolute; 
            height: 535px; 
            border: 1px solid orangered; 
            top: 10px; 
            left: 10px; 
            right: 1125px;
        }
        #content{
            position: absolute; 
            height: 400px; 
            border: 1px solid black; 
            top: 135px; 
            left: 250px; 
            right: 10px;
        }
        #header{
            position: absolute;
            height: 115px;
            border: 1px solid orange;
            left: 250px;
            right: 10px;
        }
    </style>

    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
</head>

<body>   
    <div id="parent">
        <div id="header">
            <h1>HEADER</h1>
        </div>

        <div id="palette">
            <h1>PALETTE</h1>
            <hr>
                <div class="tbutton"><img id="finishImage" src="finish.png" /></div>
        </div>
        <div id="content">
    </script> 
            <script type="text/javascript">
                $("#finishImage").draggable({ 
                    helper: "clone" 
                    });

                $("#content").droppable({                
                    drop: function(event, ui) {
                        $("#content").append("<img id='finishImage' src='as.jpg'/>");
                    }
                });
            </script>
        </div>
    </div>
</body>
</html>

Im doing Drag & Drop from div pallette to div content. Everything good but. I want to do this drop mouse location. Like window builder. My code is always drop position x:0 y:0 like this: enter image description here

How can i do "drop mouse location".


Solution

  • I added this to your JS

    $("#content").droppable({                
                    drop: function(event, ui) {
                      var pos = $("#content").position()
                      $("#content").append("<img id='finishImage' src='as.jpg' style='left: "+(event.pageX-pos.left)+"px; top: "+(event.pageY-pos.top)+"px'/>");
                    }
                  });
    

    and this to your CSS

    #content #finishImage{
     position :absolute
    }
    

    I added a top and left style attribute to the picture when its added which is judged form the mouse location (pageX/pageY) and accounts for the location of the Div(position.left/.top)

    Heres a codePen with movable objects