Question

I have a page with a list of about 500 names. The user would like to type for e.g. s on their keyboard and then the page will automatically scroll to the names starting with s.

Should I convert the first letter of those names to an INT, give that INT as a data-attribute and add a jQuery function to the page or is there a better solution?

Was it helpful?

Solution

I'd suggest to embed the list of names for each character in a div with the appropriate id, such as for the names starting with S:

<div id="S">
  ... names with S ...
</div>

Then you can use jQuery to react on a keypress, and just do a

location.href = '#S';

Then, the browser will automatically scroll to the appropriate div. Another advantage of this is that you can even use the URL to put it into your favorites, so if you want to jump directly to all people with S, you can do this easily.

Update: As the .keypress() function of jQuery only returns a number, not the character itself, you need to convert it. See Convert character to ASCII code in Javascript for an example of how to convert a character to a number and vice-versa.

OTHER TIPS

If you're looking for something a bit faster, you can do the following trick (I presume the names are ordered).

You add to the first element that has a certain letter the id="letter_X", and when the user scrolls, you just use the id as an anchor (my_url#letter_X).

This is the fastest way I know for doing this, but works for only one letter.

PS: in html5 anchors are now element ids, and can be added on any html element.

I think you should use section with an id for the tag. then do a $.scrollTop() from jquery.

$(window).scrollTop($('section#user_id').offset().top);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top