1

I have a series of elements, one beneath the next. There will be content at the top of each of these elements but a space at the bottom over which a horizontal bar will sit.

There is only one horizontal bar on the page. It needs to be 'fixed' to the bottom of the first element until that element is scrolled out of view, at which point it needs to animate to the bottom of the currently-in-view element.

I've mocked up a fiddle which shows some logic for highlighting the currently active section, which I'm happy with. The sections are grey by default. The most-in-view section as you scroll up and down turns red to indicate that it's the active section - which works fine. The horizontal bar is in blue.

What I'm struggling with is getting the blue bar to animate down to the bottom of the red section as it changes on scroll.

http://jsfiddle.net/9kW5N/2/

The main reason my code in the fiddle isn't working I think is because the window scroll event isn't 'live' so doesn't know what the currently active (red) section is.

Can anyone suggest how to achieve this?

Thanks for any pointers folks!

Briquette
  • 5,336
  • 20
  • 77
  • 129

1 Answers1

1

So I changed some code in your changeSection() function. It sort of works, but definitely not perfect. Maybe it will point you in the right direction though?

Also commented out the animation onScroll.

function changeSection() {
    $('.active').removeClass('active');
    var currentlyActive = $('section').eq(closestArrPos);
    currentlyActive.addClass('active');
    $("#horiz").animate({"top" : currentlyActive[0].offsetTop + currentlyActive.height()}, "fast");
}

DEMO : http://jsfiddle.net/9kW5N/5/

Also needed to put the window.scroll event in a setTimeOut function so it only gets called effectively after the scroll is finished rather than many times throughout.

Briquette
  • 5,336
  • 20
  • 77
  • 129
ahren
  • 15,967
  • 5
  • 44
  • 67
  • Thanks - that's useful. I'm wondering if the instability of this solution is because the function which sets the top position is called on the window.scroll event, so it's probably being called hundreds of times even for a small amount of scrolling. Do you think some kind of setTimeOut would solve this? Is there any other reason you can think of why it doesn't work so well now? I'm at the edge of my understanding of javascript here so really appreciate the advice. – Briquette Jul 05 '12 at 22:01
  • That's it! This seems much more stable and was simpler than I thought: http://jsfiddle.net/9kW5N/7/ – Briquette Jul 05 '12 at 22:06