web components

sortable-list

Make a <ul> list sortable.

code
<style>
  li {
    cursor: grab;
    margin-left: 2em;
  }
</style>
<sortable-list>
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
  </ul>
</sortable-list>
  • One
  • Two
  • Three
  • Four

Styling

Style the contained <li> elements the way you want.

code
<style>
  ul.styled {
    max-width: 150px;
    list-style: none;
    padding: 0;
  }
  ul.styled li {
    padding: 0.5em;
    border: solid 1px var(--color);
    border-radius: 0.3em;
    margin-bottom: 0.2em;
    margin-left: 0;
  }
</style>
<sortable-list>
  <ul class="styled">
    <li style="color: white; background-color: indianred">One</li>
    <li>Two</li>
    <li style="color: white; background-color: steelblue">Three</li>
    <li style="color: white; background-color: lightseagreen">Four</li>
  </ul>
</sortable-list>
  • One
  • Two
  • Three
  • Four

Event

It emits a "sorted" event where e.detail is an array of HTMLLIELements.

code
<sortable-list id="sort-event">
  <ul class="styled">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
  </ul>
</sortable-list>
<p id="result"></p>
<script>
  document.querySelector("#sort-event")
  .addEventListener("sorted", (e) => {
    document.querySelector("#result")
      .textContent = `Sorted: ${
        e.detail.map((li) => li.textContent)
      }`;
  });
</script>
  • One
  • Two
  • Three
  • Four