January 28, 2024 5:01 am

How to drag and drop items using jQuery

I have receive many requests from my readers to write something about dragging items using jQuery, so today I am going to write about jQuery dragging with sortable to do that I have used jQuery UI library. Its a very simple to understand and implement have a look on the script.

how-to-drag-and-drop-items-using-jquery

[wpdm_file id=39]

 

HTML page which required to create boxes.

<div class="drag" id="drag">
    <div class="box black">
        <div class="box-head">
            <h4>Title 1</h4>
        </div>
        <div>Content 1</div>
    </div>
    <div class="box red">
        <div class="box-head">
            <h4>Title 2</h4>
        </div>
        <div>Content 2</div>
    </div>
    <div class="box blue">
        <div class="box-head">
            <h4>Title 3</h4>
        </div>
        <div>Content 3</div>
    </div>
</div>

jQuery methods call and include js libraries:

<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$("#drag").sortable({
connectWith: ".box",
items: ".box",
opacity: 0.5,
forcePlaceholderSize: true,
tolerance: "pointer"
});
</script>

sortable used to make all items in order.

$(“#drag”) id of your div area in which you can drag and drop items.

opacity: 0.5 is used to show the shade of item which you are moving.

CSS for style the boxes in your page

<style type="text/css">
*{
    font-family:Tahoma, Geneva, sans-serif;
}
h4{
    color:#FFF;
}
.drag{
    width:100%;
    margin:0 auto;
}
.box{
    padding:10px;
    min-height:160px;
    text-align:justify;
    border:0px #CCC solid; 
    margin:5px;
}
.box-head{
    cursor:move;
}
.black{
    border:#000000 1px solid;
}
.black h4{
    background-color:#000000;
    padding:10px;
}
.red{
    border:1px #FF0000 solid;
}
.red h4{
    background-color:#FF0000; padding:10px;
}
.blue{
    border:#0000FF 1px solid; }
.blue h4{
    background-color:#0000FF;
    padding:10px;
}
</style>

Feel free to comment we love to answer you.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

One response to “How to drag and drop items using jQuery”

  1. eko says:

    I am wondering how would i save changes to this, so blocks stay in order i move them around… Thinking to use it for blocks on my website or similar?

Leave a Reply

Your email address will not be published. Required fields are marked *