MEM
MEM

Reputation: 31367

Animate stops scrolling as expected. Any clue?

Here's the fiddle: http://jsfiddle.net/talofo/5YgY5/19/

Steps to see the issue:

  1. Click on "ble ble" menu item
  2. Click inside the yellow section
  3. Click on "bla bla" menu item
  4. Click again on "ble ble" menu item.

You will notice that the 4) step will NOT work, and we will NOT have a scroll back to that item, because, so I believe, we have change the ID.

var $root = $('html, body');

$('.main-menu a').click(function() {
 $root.animate({
   scrollTop: $($(this).attr('href')).offset().top+1
  }, 2000
 );
 return false;
});

I have tried to change this code a lot, but I was getting nowhere, so I end up giving up posting garbage, and leave the issue code only.

Can anyone please advice on how can we fix this behavior?

Upvotes: 0

Views: 40

Answers (1)

Fresheyeball
Fresheyeball

Reputation: 30015

You are checking for the offset of an element based on the id of the element on click. So if you change that id, the next time you click, the query $($(this).attr('href')) will fail (it no longer matches anything). Therefore the .offset().top will not be a number causeing the animation to then fail.

To fix this get the offsets once outside the click listener, this way you are not querying on click, and future clicks will simply be tied to the original offset.

DEMO

  var $root = $('html, body');
  $('.main-menu a').each(function(){
      // capture the offset on init not click
      var that   = $(this),
          offset = $(that.attr('href')).offset().top+1;
      // then use that offset, so we are not querying for id on each click
      that.click(function() {
         $root.animate({
           scrollTop: offset
         }, 2000);
      });      
  }); 

Upvotes: 2

Related Questions