Simple Sort By functionality for Shopify Themes

Searching for how to implement standard sort_by functionality in Shopify is a mixed bag.  The official support for this functionality does not work well in custom themes.  Simply dropping in the code they provide does not work. 

(https://help.shopify.com/themes/customization/collections/add-sort-order-menu)

The HTML provided by the official example is fine.

<label for="sort-by">Sort by</label>
<select id="sort-by">
  <option value="manual">Featured</option>
  <option value="price-ascending">Price: Low to High</option>
  <option value="price-descending">Price: High to Low</option>
  <option value="title-ascending">A-Z</option>
  <option value="title-descending">Z-A</option>
  <option value="created-ascending">Oldest to Newest</option>
  <option value="created-descending">Newest to Oldest</option>
  <option value="best-selling">Best Selling</option>
</select>

I’ve modified the Javascript to work with a little less complexity

  // Collection sort functionality
  Shopify.queryParams = {}; 
  // get the url from the window object
  var url = window.location.href; 
      // turn the string into a url object
      url = new URL(url);
      // if the parameter youre looking for exists grab that parameter. If not, set the default.
      param = ( url.searchParams.get('sort_by') )? url.searchParams.get('sort_by') : 'manual';

  // event handler on change for sort by
  $('#sort-by').on('change', function(e){ 
    // get the value of the selection
    Shopify.queryParams.sort_by = $(this).val(); 
    // reload the page with the new url param
    location.search = $.param(Shopify.queryParams).replace(/\+/g, '%20');
    // this sets the param on page load to be default 
    // or the param in the URL youre currently viewing.
  }).val(param); 

Piece of cake.