jquery-uijquery-ui-draggable

set draggable in mousedown handler


Perhaps it's by design, but I want the handle to be draggable rightaway, not after the first mouseup as it currently happens.

<html>
<head>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>
    <script>
        $(function () {


            var handle = $("#handle");

            handle.on("mousedown", function () {

                // doesn't work
                handle.draggable();
            });


            // works
            handle.draggable();
        });
    </script>
</head>
<body>
    <div style="width: 400px; height: 400px; border: 2px solid gray; position: relative;">

        <div id="handle" style="width: 50px; height: 50px; position: absolute; top: 100px; left: 100px; background-color: gray;"></div>
    </div>
</body>
</html>

Solution

  • I'm not really sure what you're trying to accomplish but your example demonstrates the correct behaviour.

    If you init the .draggable() in the mousedown event it just means that the handle div gets initialized to be draggable when you first click on the div. After that it gets initalized again and again. So on page load your div doesn't know it has to be draggable. If you then click on it your mousedown event triggers and sets the div to be draggable.

    If you want it to be draggable rightaway just use your second - working - example. It's perfectly fine or am I missing something? See this jsfiddle

    The Default Functionality example in the jQuery UI documentation shows exactly this.

     $(function() {
        //element with ID "draggable" is draggable after the DOM has loaded
        $( "#draggable" ).draggable();
    });
    

    There's simply no need to wrap the .draggable() in a mousedown event.