DEV Community

Michael Burrows
Michael Burrows

Posted on • Edited on • Originally published at w3collective.com

Drag & drop quiz component with SortableJS

*** CodePen Demo ***

SortableJS is a JavaScript library for building re-orderable drag and drop ui elements.

As an introduction to the library we’ll build a quiz that requires the user to correctly order a set of answers.

Alt Text

SortableJS can be downloaded from here or loaded via CDN.

<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

In this example we’ll ask the user to sort a list of F1 drivers by their number of Grand Prix victories.

Let’s get started by creating the following HTML list with the driver names:

<!-- index.html -->
<ul id="quiz">
  <li>Ayrton Senna</li>
  <li>Sebastian Vettel</li>
  <li>Lewis Hamilton</li>
  <li>Fernando Alonso</li>
  <li>Michael Schumacher</li>
  <li>Alain Prost</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

Next we initiate SortableJS, passing the id of our “quiz” element.

// script.js
new Sortable(quiz);
Enter fullscreen mode Exit fullscreen mode

At this point you should be able to drag the list items to change the order in the browser.

Next we’ll add a button to the HTML that can be clicked to check if the answer is correct:

<!-- index.html -->
<button onclick="checkAnswer()">Check Answer</button>
Enter fullscreen mode Exit fullscreen mode

Then define the correct order that the drivers need to be sorted:

// script.js
const correctAnswers = [
  "Michael Schumacher",
  "Lewis Hamilton",
  "Sebastian Vettel",
  "Alain Prost",
  "Ayrton Senna",
  "Fernando Alonso",
];
Enter fullscreen mode Exit fullscreen mode

In the checkAnswer function we push the users answer to an array and then compare with the correctAnswers.

// script.js
function checkAnswer() {
  const li = document.querySelectorAll("#quiz li");
  let answers = new Array();
  li.forEach(function (text) {
    answers.push(text.innerHTML);
  });
  if (JSON.stringify(correctAnswers) === JSON.stringify(answers)) {
    alert("Correct :)");
  } else {
    alert("Try Again...");
  }
}
Enter fullscreen mode Exit fullscreen mode

Lastly we’ll add some basic styling and change the cursor style to indicate the list items are draggable.

/* style.css */
#quiz li {
  display: block;
  background-color: lightsteelblue;
  padding: 10px;
  border-bottom: 1px solid #fff;
  cursor: move;
  cursor: -webkit-grabbing;
}
#quiz li.sortable-chosen {
  background-color: lightslategray;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)