2

I'm trying to create using jquery a draggable list into a sortable list.

Everything works, except when using CSS to transform this list into a grid. As soon as everything is displayed as a grid, the draggable into the sortable stops to work.

My HTML is:

<ul id="sortable2">
  <li class="ui-state-highlight">A</li>
  <li class="ui-state-highlight">B</li>
  <li class="ui-state-highlight">C</li>
  <li class="ui-state-highlight">D</li>
</ul>

<ul id="sortable">
  <li class="ui-state-default">1</li>
  <li class="ui-state-default">2</li>
  <li class="ui-state-default">3</li>
</ul>

My page SCRIPT is:

$(function() {
   $("#sortable").sortable();
   $("#sortable2 li").draggable({
      connectToSortable: "#sortable",
      helper: "clone"
   });
});

And the CSS I've added to make both UL display as grid is:

#sortable {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 450px;
}
#sortable li {
  margin: 3px 3px 3px 0;
  padding: 1px;
  float: left;
  width: 100px;
  height: 90px;
  font-size: 4em;
  text-align: center;
}
#sortable2 {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 450px;
}
#sortable2 li {
  margin: 3px 3px 3px 0;
  padding: 1px;
  float: left;
  width: 100px;
  height: 90px;
  font-size: 4em;
  text-align: center;
}

Any ideas?

I'm using jquery-ui.css, jquery-ui.js and jquery.min.js.

Thanks

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Richasantos
  • 576
  • 2
  • 8
  • 15

1 Answers1

1

The reason this is occurring is because the children li elements are floated.

When an element is floated, it is essentially removed from the normal document flow, and in this case results in the parent element collapsing upon itself with a height of 0:

enter image description here

As a result, you can't drop elements into the #sortable element because it doesn't have a height.

The most common work-around is to use a clearfix to prevent the parent element from collapsing.

Either add overflow: auto to the container element (example):

ul {
  overflow: auto;
}

or use a pseudo-element (example):

ul:after {
  content: '';
  clear: both;
  display: table;
}

Alternatively, you could also just remove float: left from the li elements and set their display to inline-block instead. Additionally, vertical-align: top should be added to resolve a minor alignment issue when dragging the elements (example):

ul li {
  display: inline-block;
  vertical-align: top;
}
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Thanks mate. It worked.I ended up using this: #sortable:after { clear:both; content:'.'; display:block; height:0; line-height:0; font-size:0; visibility:hidden; padding:0; margin:0; } – Richasantos Dec 15 '15 at 11:07