jQuery UI Sortable Drag and Drop

jQuery ui has an amazing plugin that will help you make drag and drop web application in a very easy and simple way. We will use jQuery ui sortable plugin to make a simple sortable drag and drop list. jQuery ui really made it easy to make an amazing drag and drop applications. Here is what we are going to make from scratch.

[codepen_embed height=”357″ theme_id=”dark” slug_hash=”RRNbbO” default_tab=”result” user=”Hujjat”]See the Pen <a href=’http://codepen.io/Hujjat/pen/RRNbbO/’>jQuery ui Sortabl plugin</a> by Hujjat Nazari (<a href=’http://codepen.io/Hujjat’>@Hujjat</a>) on <a href=’http://codepen.io’>CodePen</a>.[/codepen_embed]

How to Use jQuery UI Sortable?

As like every other jQuery ui plugins, using sortable plugin is also the same and easy. All you need is to add jQuery and jQuery ui. You can download them from jQuery site.

Let’s add some html and css to start designing our sortable list. here the basic html markup(Of course you can customize it).

<ul id="sortable">  
    <li class="item-1">Item 1</li>  
    <li class="item-2">Item 2</li>  
    <li class="item-3">Item 3</li>  
    <li class="item-4">Item 4</li>  
</ul>

and Here some CSS for styling.

@import url(https://fonts.googleapis.com/css?family=Lato);

body {
  margin: 0px;
  padding: 0px;
  background: #303030;
  font-family: 'Lato', sans-serif;
}

h1 {
  color: #fff;
  text-align: center;
  margin-top: 2em;
}

ul {
  list-style: none;
  margin-top: 2em;
}

ul li {
  color: #fff;
  padding: 20px;
  width: 500px;
  margin: 0px auto;
  cursor: pointer;
}

ul li.item-1 {
  background: #5BC0EB
}

ul li.item-2 {
  background: #9BC53D
}

ul li.item-3 {
  background: #E55934
}

ul li.item-4 {
  background: #FA7921
}

Coming to JavaScript part, it’s pretty simple. If you have not yet link to jQuery and jQuery ui, you can link them through cdn.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

I assume you have a added them at the bottom of your page. Now let’s write our JavaScript code to preform the action.

 $(function() {
   $("#sortable").sortable();
 });

We used jQuery to select the  sortable id and than we applied th sortable function to it. Now, our list will be sortable. We can change the order the way we want.

Conclusion

It was how jQuery ui sortable plugin works. You can use it in any project you want in the same way. We hope it has been informative for you. If you have any questions related to this content, feel free to comment it bellow. 🙂

 

Coding TipsJavaScriptJavaScript FrameworkjQueryjQuery UI
Comments (0)
Add Comment