How to add a unique id to first of kind

231 Views Asked by At

ok. Building out a employee directory. At the top of the directory is the alphabet so you can click on a letter an arrive at the first person who has that letter as first letter of last name. How can i loop through the all of the employees and add an id of the letter to the first of each. I haven't built out the markup, yet, but for now it could be as simple as

<h3><span class="fname">Johnny</span><span class="lname">Willis</span></h3>
</div> ```

Where I would target the last name and add an ID to the card
I am pulling all of the content in from a hubspot hubdb.  Unsure if that is relevant, but wanted to add that.
1

There are 1 best solutions below

1
On

I think you don't need to add an ID to each of the last names from your list. If you just want to scroll down to the first item when clicking the alphabet index, try this:

HTML

<!-- A container for the alphabet letters -->
<div id="alphabet">
  <span id="letter-a">A</span>
  <span id="letter-b">B</span>
  <span id="letter-c">C</span>
  <span id="letter-d">D</span>
</div>

<!-- A container for each last name -->
<div id="employee-a" style="height:500px">
  <p>A</p>
  <p>Adams Mike</p>
  <p>Addison John</p>
  <p>Adkins Smith</p>
</div>
<div id="employee-b" style="height:500px">
  <p>B</p>
  <p>Bain Chris</p>
  <p>Barker Travis</p>
  <p>Banner Brock</p>
</div>
<div id="employee-c" style="height:500px">
  <p>C</p>
  <p>Carl Steve</p>
  <p>Carter Aaron</p>
  <p>Castle Vania</p>
</div>
<div id="employee-d" style="height:500px">
  <p>D</p>
  <p>Daenerys Targaryen</p>
  <p>Dale Denton</p>
  <p>Daniels Jack</p>
</div>

JAVASCRIPT

<script>
  // Wait until DOM is fully loaded
  $(document).ready(function() {
    // Get the ID name from the letter you clicked
    $('#alphabet > span').on('click', function() {
      // Pass this ID name to a variable
      var letter = $(this).attr('id');
      var goTo = letter.split('-').pop();
      // Use it to smooth scroll to the position of the first last name with the letter you clicked
      $('html, body').animate({
        scrollTop : $('#employee-' + goTo).offset().top
      }, 500);
    })
  });
</script>

Hope this helps.

Enjoy!