user1332983
user1332983

Reputation: 13

Javascript/Jquery to make Anchor links down to the first instance of a specific class...?

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

Answers (3)

Sampson
Sampson

Reputation: 268364

Works with Plain HTML

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. -->

JavaScript / jQuery Method

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

Sang Suantak
Sang Suantak

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

Terry
Terry

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

Related Questions