Question

I'm trying to scroll a set of DIV(PHP generated) with the same CLASS individually when an LI with index equivalent INDEX is clicked. Any idea on how this can be achieved.

HTML

<ul class="bar-transport">
  <li><a href="Affordable">Affordable</a></li>
   <li><a href="reliable">Reliable</a></li>
<li><a href="#">Responsive</a></li>
</ul>
      <div class="topic-intro">One</div>
        <div class="topic-intro">Two</div>
      <div class="topic-intro">Three</div>

jQuery

jQuery(document).ready(function($) {

    $("ul.bar-transport li a").click(function(event){       

        event.preventDefault();
        $('html,body').animate({scrollTop: $($(this).attr('href')).offset().top}, 1700);
    });

});
Was it helpful?

Solution

If I understood correctly, you want something like this:

$('a').click(function(e) {
    e.preventDefault();
    var link_index = $(this).index('a');
    var div = $('.topic-intro').eq(link_index);
    $('html body').animate({
        scrollTop: div.offset().top - 10
    }, 300);
});

Demo: http://jsfiddle.net/WN5Tr/1/

The thing is, I personally would not work with indexes in this case as this solution is error-prone. I would work with unique href - id pairs, so structure like this:

<a href="#section1">
<a href="#section2">
<a href="#section3">

<div id="section1"></div>
<div id="section2"></div>
<div id="section3"></div>

OTHER TIPS

That works but I had to create a function that assigns ID's to the DIV(onload) becasue they're dynamically generated. See the functin bellow.

HTML

<ul class="bar-transport">
<li><a href="#affordable">Affordable</a></li>
<li><a href="#expandable">Expandable</a></li>
<li><a href="#responsive">Responsive</a></li>
</ul>

Script

   jQuery(document).ready(function ($) {
        $h = jQuery.noConflict();
        console.log($h)
        $h("body > .ti").attr('id', 'affordable');
        $h("body > .ti + .ti").attr('id', 'expandable');
        $h("body > .ti + .ti + .ti").attr('id', 'responsive');
    });


 jQuery(document).ready(function($) {

    $("ul.bar-transport li a").click(function(event){       

        event.preventDefault();
        $('html,body').animate({scrollTop: $($(this).attr('href')).offset().top}, 1700);
    });

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top