Jonathan
Jonathan

Reputation: 23

JQuery, ScrollTop scrolls to last div and not ID div

So im basically using a link, to scroll through a series of divs to select the correct one. Ie click on happy, and scrolls to 'happy' div,

However, the scroll seems to not go to what its linked to, but scrolls to the third div in the list.

Heres the code:

<div id="portfoliowrapper">
        <div class="title">My Portfolio</div>
        <div class="row1"><a id="kazookilink" href="#">Kazooki</a></div>
        <div class="row1"><a id="uodlink" href="#">Universe of Downhill</a></div>
        <div class="row1"><a id="kudialink" href="#">Kudia</a></div>
    </div>
    <div id="description">
        <div id="top">description</div>
        <div id="kazooki">kazooki</div>
        <div id="uod">Universe of Downhill</div>
        <div id="kudia">kudia</div>
    </div>



 <script type="text/jscript">

      function goToByScroll(id){
      id = id.replace("link", "");    
      $("#description").animate({scrollTop: $("#"+id).offset().top},'slow');
      };

      $(".row1 > a").click(function(e) { 
        // Call the scroll function
      goToByScroll($(this).attr("id"));           
      });

 </script>

Upvotes: 2

Views: 2030

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Need to use position() instead of offset() and also need to set the #description to be position:relative.

Then you need to factor in the current scrollTop.

Last you need to cancel the default click behavior.

Complete example at http://www.jsfiddle.net/gaby/TneA6/

Upvotes: 1

stefanw
stefanw

Reputation: 10570

I guess you need to prevent the usual behaviour of the click:

  $(".row1 > a").click(function(e) { 
        // prevent default behaviour
        e.preventDefault();
        // Call the scroll function
        goToByScroll($(this).attr("id"));           
  });

Just guessing though.

Upvotes: 0

Ben Lee
Ben Lee

Reputation: 53319

It's probably just scrolling to the very bottom of the page -- it can't align the top of the div with the top of the page because the page ends. Try adding a bunch of empty space at the bottom of the page (a <div style='height: 1000px;"></div> or something) and see if it still results in the unexpected behavior.

Upvotes: 0

Related Questions