Reputation: 13
My brain is fried and I can't wrap my head around this. I'm definitely a newbie at programming.
In my page I have a dynamically generated list of names displayed alphabetically. Everyone with a last name that starts with an 'A' gets the css class 'letter_A'. Every person with a last name that starts with a 'B' gets the css class 'letter_B' and so on...
I have a list of anchor links (A - B - C - D - E - F - G - H - I and so on) at the top of the page that I want to jump down to the first item (name) that has a specific class. So the anchor link "A" would jump down to the first item that has the class 'letter_A'. The anchor link "B" would jump down to the first item that has the class 'letter_B' and so on.
What would be the best way to write this using javascript (or jquery)?
Upvotes: 0
Views: 808
Reputation: 268364
You really wouldn't need jQuery or JavaScript for this. You could used simple named-anchors:
<a href="#B">B Names</a> <!-- Clicking me... -->
...
<a id="B"> <!-- Will scroll down to me. -->
If you need to use jQuery, the following would work:
// Bind to all <a href="#B">B</a> within <ul class="letters">
$(".letters").on("click", function(e){
e.preventDefault();
// Ease the body's scrollTop value to our first matched letter
$("body").animate({
scrollTop: $(".letter_" + this.innerHTML).position().top
}, 2000);
});
Upvotes: 0
Reputation: 5265
This should do the job:
$("a").click(function(){
var firstItem = $(".letter_" + $(this).text()).first();
var top = firstItem.offset().top;
$("body,html").scrollTop(top);
});
Upvotes: 1
Reputation: 14219
I'm tired and shouldn't be writing answers right now but you could try something like this
$("a").click(function(e) {
e.preventDefault();
var offset = $('.letter_' + $(this).attr('href') + ':first').offset().top; // find the scroll position of the class with letter_(whatever you clicked on)
$('html, body').animate({ scrollTop:offset }, 300); // scroll to that position
});
Upvotes: 0