Scroll to the first element that starts with a character using jQuery

I have a fairly long list of names, and I would like to create a quick, easy navigation to scroll through the names starting with a specific character.

So, if I had links like -

<a href="a">A</a>
<a href="b">B</a>
<a href="c">C</a>

I usually had anchors or divs with identifiers set between characters and scrolling to them. In this case, I do not have anchors or divs before each new letter of the beginning, I just have a long list.

Let's say that every name in the list is in <h1 class="name">Someone Name</h1>

I can get a letter from

$('a').click(function(e) {
    e.preventDefault();
    var letter = $(this).attr('href');
    //scroll to first h1.name element that begins with "letter"
 });

So, as soon as I have this letter, is there a way to find the first element that is h1.namewhich starts with this letter using jQuery?

+3
source share
2 answers

, filter() h1 letter ( )

$('a').click(function (e) {
    e.preventDefault();
    var letter = $(this).attr('href');
    //scroll to first h1.name element that begins with "letter"
    var $target = $('h1.name').filter(function () {
        return $.trim($(this).text()).toLowerCase().indexOf(letter) == 0
    });
    //scroll to $target
});

: contains() , , .

+3

, :

var letters = {};

$('h1.name').each(function() {
    // find first letter of element contents
    var letter = (this.textContent || this.innerText || '').toLowerCase()[0];

    if (letter && !(letter in letters)) {
        letters[letter] = this; // add to cache
    }
});

:

$('a').on('click', function(e) {
    e.preventDefault();

    // use last letter of anchor
    var letter = this.getAttribute('href').toLowerCase();

    if (letter in letters) {
        letters[letter].scrollIntoView();
    }
});

+2

All Articles