5

Following the examples in the jQuery UI demo and documentation, I'm using this HTML:

<ul class="sort">
  <li>
    <button>A</button>
  </li>
  <li>
    <button>B</button>
  </li>
  <li>
    <button>C</button>
  </li>
</ul>

And this JS:

$(function () {
  $('.sort').sortable();
})

But as seen in this JSFiddle example, the buttons are not drag-able.

How can I make .sortable() work with buttons?

2 Answers 2

11

Sortable provides a cancel selector to prevent sorting on specified elements. The default value includes <button> elements, and your sort handles are buttons, so sorting is prevented:

cancel
Type: Selector
Default: "input,textarea,button,select,option"
Prevents sorting if you start on elements matching the selector.

To solve this, set the cancel selector to an empty string:

$('.sort').sortable({
  cancel: ''
});
ul {
  list-style: none;
  margin: 0;
  padding: 0;
  width: 100px;
}

button {
  width: 100%;
}
<link href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<ul class="sort">
  <li><button>A</button></li>
  <li><button>B</button></li>
  <li><button>C</button></li>
</ul>

View on JSFIddle


Also, you can specify the draggable handles for sortable() by using the handle option:

$('.sort').sortable({handle:'button'});

But in your case, the entire content of each <li> element is a <button>, so you won't need to specify it.

Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it! Thanks a lot!
after almost 1 decade, this answer is still relevant 🙈
3

Ahhh, you know what? jQuery UI prevents .sortable() from working on buttons by default, as stated in the .cancel() section of the documentation! Clearing this default allows the buttons to be sort-able like in this updated example.

The functional JS/jQuery looks like this:

$(function () {
  $('.sort').sortable({
    cancel: ''
  });
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.