jQuery Drag and Drop DOM Element in Browser

jQuery drag and drop HTML element in browser

In jquery, we can make any DOM element is draggable or droppable using draggable or droppable functionalities.

jQuery draggable method syntax

$(selector).draggable();

jQuery droppable method syntax

$(selector).droppable({
                drop: function (event, ui) {
                 // jQuery code changes when dropping dragged element
                }
            });

This page explains how to implement drag and drop feature in JQuery code for any web page.

jQuery Example to implement drag and drop feature

This jQuery code is used to enable div element draggable which can be moved anywhere in the browser and dropped inside of droppable div element.

here div element is selected using id 'divTitle' and enabled as draggable and div element id 'divMain' is enabled as droppable.

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>jQuery animate method</title>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#divTitle").draggable();
            $("#divMain").droppable({
                drop: function (event, ui) {
                    $(this)
                        .css("background-color", "green")
                        .html("Dropped!");
                }
            });
        });
    </script>
</head>
<body>
    <div id="divTitle" style="height:200px;width:200px;background-color:blue;color:white;">
        div element draggable testing!
    </div>
    <br/>
    <div id="divMain" style="height:400px;width:400px;background-color:red;color:yellow;">
        div element droppable testing!
    </div>
</body>
</html>
Output:

draggable div element

draggable and droppable div elements

After moving the draggable div element

after dragging div element in the draggable div element

How to disable droppable for any element in jQuery?

disabled attribute is available in droppable method in jQuery to disable any element is droppable.

            $("#divMain").droppable({
                disabled: true
            });

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^