Alphabetical Index

Create an automatic Alphabetical Index with JS
Tagged: jsFriday, June 21, 2019

Build a Dynamic Alphabetical Index from a List with jQuery

This was a quick sample I whipped up for a project and didn't end up using, but I had a long list of terms, and wanted a way for a user to jump down to a section of the list.

This uses Bootstrap and its Pagination classes to generate an index with links for letters found in the list, and disabled links if that letter wasn't found.

<ul class="list-wrapper">
  <li>
    <h3>Ant</h3>
  </li>
  <li>
    <h3>Cat</h3>
  </li>
  <li>
    <h3>Dog</h3>
  </li>
  <li>
    <h3>Dingo</h3>
  </li>
  <li>
    <h3>Whale</h3>
  </li>
</ul>
jQuery(document).ready(function($) {
  // Create an Alphabetical jump list
  // Look at h3 tags in the list
  var listItems = $(".list-wrapper h3").sort();

  var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  var glossaryHTML = "";
  for (var i = 0; i < letters.length; i++) {
    var thisLetter = letters.charAt(i);

    // Need to find first of each letter
    var foundOne = -999;
    for (var j = 0; j < listItems.length; j++) {
      var itemText = listItems[j].innerText.toUpperCase();
      if (itemText.charAt(0) == thisLetter) {
        foundOne = j;
        break;
      }
    }

    // Create links and anchors based on whether something was found
    if (foundOne == -999) {
      // letter not found
      glossaryHTML +=
        '<li class="disabled"><a class="page-link">' + thisLetter + "</a></li>";
    } else {
      // We found an item with a letter
      glossaryHTML +=
        '<li class="page-item"><a class="page-link" href="#glossary-' +
        thisLetter +
        '">' +
        thisLetter +
        "</a></li>";
      // Create an anchor for the first letter found
      $(listItems[foundOne]).attr("id", "glossary-" + thisLetter);
    }
  }
  // after the pagination html is built insert it to the page
  $(".list-wrapper").before(
    "<nav aria-label='Alphabetical Navigation'><ul class='pagination'>" +
      glossaryHTML +
      "</ul></nav>"
  );
});

See the Pen Automatic Alphabetical Index with JS by Nicholas (@NickStees) on CodePen.