Sahil Dhir
Sahil Dhir

Reputation: 4250

Drag particular part from a list in ul using jquery UI?

I have a list containing text and arrows. I want to drag or sort arrows in such a way that :

  1. They can be dragged from 1 list to other.
  2. The red arrow cannot come before green arrow i.e red arrow always above green and if someone try to drag above it , it should not be possible and it resides below red only.

This is what i have tried so far:

$("ul.droptrue").sortable({
  connectWith: "ul"
});
.green {
  color: green
}

.red {
  color: red;
}

li,
ul {
  list-style: none;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<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>
<ul class="droptrue">
  <li>i am a text 1 <i class="fa fa-arrow-left red"></i> </li>
  <li>i am a text 2 <i class="fa fa-arrow-left green"></i> </li>
  <li>i am a text 3 </li>
  <li>i am a text 4 </li>
  <li>i am a text 5 </li>
  <li>i am a text 6 </li>
</ul>

Problem:

Right now the whole list is dragging and I want only arrow to drag.

Thanks in Advance

Happy Coding.

Upvotes: 2

Views: 168

Answers (1)

Abhishek Pandey
Abhishek Pandey

Reputation: 13558

You can use update() event and compare offset of both arrows, if condition doesn't match then use cancel() method to cancel sorting.

$(document).ready(function() {
  $("ul.droptrue li").sortable({
    connectWith: "li",
    items: "> i",
    update: function(event, ui) {
      var redArrow = $('.fa.fa-arrow-left.red').offset().top;
      var greenArrow = $('.fa.fa-arrow-left.green').offset().top;
      if (redArrow >= greenArrow) {
        $("ul.droptrue li").sortable("cancel");
        console.log("Red arrow cannot be greater than Green arrow")
      }
    }
  });
})
.green {
  color: green
}

.red {
  color: red;
}

li,
ul {
  list-style: none;
}

ul {
  width: 100px
}

li div {
  display: inline-block
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<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>
<ul class="droptrue">
  <li>
    <div>i am a text 1</div> <i class="fa fa-arrow-left red pull-right"></i> </li>
  <li>i am a text 2 <i class="fa fa-arrow-left green pull-right"></i> </li>
  <li>i am a text 3 </li>
  <li>i am a text 4 </li>
  <li>i am a text 5 </li>
  <li>i am a text 6 </li>
</ul>


Edit: added items: "> i" (item selector) in sortable() this will specify which element inside the parent element should be sortable.

Upvotes: 1

Related Questions