Question

I have a single page site:

http://chiaroscuro.telegraphbranding.com/

Each section is dynamically sized based on the user's window. I'm trying to figure out how to have a jQuery smooth scroll function scroll to the top of each section when the link is clicked. It is working great for the first section, funding areas, where I just used a simple offset().top, but the others are not working because they don't know how far to scroll because the window size is always different.

I've been trying to get offset() or position() to work, but no dice. I appreciate any advice.

Here's my jQuery:

`

$(document).ready(function () {
    var slowScrollFunding = $('#funding-areas').offset().top;
    var slowScrollAbout = $('#about-us').offset().top;
    var slowScrollProjects = $('#our-projects').offset().top + 600;
    panelOpen = true;
    $('#anchor-funding-areas').click(function(event) {
        event.preventDefault();
        if(panelOpen == true) {
            $('#slide-panel-content').stop(true, true).animate({height: '0px'}, 600, function() {
                $('#panel-content-container').hide();
                $('.scrollableArea').css('z-index', '11');
                // Scroll down to 'slowScrollTop'
                $('html, body, #home-wrap').animate({scrollTop:slowScrollFunding}, 1000);
                panelOpen = false;
            });
        }else{
            $('html, body, #home-wrap').animate({scrollTop:slowScrollFunding}, 1000);
        };
    });
    $('#anchor-aboutus').click(function(event) {
        event.preventDefault();
        if(panelOpen == true) {
            $('#slide-panel-content').stop(true, true).animate({height: '0px'}, 600, function() {
                $('#panel-content-container').hide();
                $('.scrollableArea').css('z-index', '11');
                // Scroll down to 'slowScrollTop'
                $('html, body, #aboutus-wrap').animate({scrollTop:slowScrollAbout}, 1000);
                panelOpen = false;
            });
        }else{
            $('html, body, #home-wrap').animate({scrollTop:slowScrollAbout}, 1000);
        };
    });
    $('#anchor-ourprojects').click(function(event) {
        event.preventDefault();
        if(panelOpen == true) {
            $('#slide-panel-content').stop(true, true).animate({height: '0px'}, 600, function() {
                $('#panel-content-container').hide();
                $('.scrollableArea').css('z-index', '11');
                // Scroll down to 'slowScrollTop'
                $('html, body, #home-wrap').animate({scrollTop:slowScrollProjects}, 1000);
                panelOpen = false;
            });
        }else{
            $('html, body, #home-wrap').animate({scrollTop:slowScrollProjects}, 1000);
        };
    });
    $('#header-logo').add('.homelink').click(function() {
        if(panelOpen == false) {
            $('.scrollableArea').css('z-index', '0');
            $('#panel-content-container').show();
            $('#slide-panel-content').stop(true, true).animate({height: '389px'}, 600, function() {
                // Scroll down to 'slowScrollTop'
                panelOpen = true;
            });
        };
    });
});

`

Was it helpful?

Solution

$.offset and $.position can be a little unreliable, especially if you have lots of complicated layouts going on - as your page does. What I've used in the past is the following trick:

var de = document.documentElement ? document.documentElement : document.body;
var elm = $('get_your_anchor_element').get(0);
var destScroll, curScroll = de.scrollTop;

/// check for the function scrollIntoView
if ( elm.scrollIntoView ) {
  /// get the browser to scrollIntoView (this wont show up yet)
  elm.scrollIntoView();
  /// however the new scrollTop is calculated
  destScroll = de.scrollTop;
  /// then set the scrollTop back to where we were
  de.scrollTop = curScroll;
  /// you now have your correct scrollTop value
  $(de).animate({scrollTop:destScroll});
}
else {
  /// most browsers support scrollIntoView so I didn't bother
  /// with a fallback, but you could just use window.location
  /// and jump to the anchor.
}

The above can occur on the click event. The only thing that needs to be improved is that different browsers scroll on different base elements (body or html). When I used this I had my own element that was scrollable so I didn't need to work out which one the agent was using... When I get a second I'll see if I can find a good bit of code for detecting the difference.

The above has worked in all the modern browsers I've tested (Firefox, Safari, Chrome) however I didn't need to support Internet Explorer so I'm not sure with regard to that.

update:

I'm not quite sure what is going on with your implementation - it is possible that the page is so heavy with content that you actually can see the .scrollIntoView() happening - this has never been my experience, but then I didn't have so much going on on-screen. With that in mind, I've implemented a bare bones system that I would advise you use and build each extra part you need into it:

http://pebbl.co.uk/stackoverflow/13035183.html

That way you know you have a working system to start with, and will easily detect what it is that stops it from working. With regards to chiaro.js your implementation seems to be ok - if a little exploded over many different areas of the file - however this part is slightly erroneous:

$('#anchor-aboutus').click(function() {
    event.preventDefault();
    if(panelOpen == true) {
        $('#slide-panel-content')
                      .stop(true, true)
                      .animate({height: '0px'}, 600, function() {
            $('#panel-content-container').hide();
            $('.scrollableArea').css('z-index', '11');
            elm.scrollIntoView(true)
                              .animate({scrollTop:destScroll}, 1000);
            panelOpen = false;
        });
    }else{
        elm.scrollIntoView(true).animate({scrollTop:destScroll});
    };
});

In the code above you will only get the correct value of destScroll if panelOpen === true. Ahh, actually I've also spotted another problem - which will explain why it's not working:

elm.scrollIntoView(true)
  .animate({scrollTop:destScroll}, 1000);

The above code is mixing pure JavaScript and jQuery, the elm var is a normal DOM element (this supports the scrollIntoView method). But you are then attempting to chain the animate method of jQuery into the mix - you should also be triggering the animate method on the element responsible for the scrollbar. What you should use is as follows:

$('#anchor-aboutus').click(function(e) {
  var currentScroll, destScroll;
  e.preventDefault();
  if(panelOpen == true) {
    $('#slide-panel-content')
      .stop(true, true)
      .animate({height: '0px'}, 600, function() {
        $('#panel-content-container').hide();
        $('.scrollableArea').css('z-index', '11');
        currentScroll = de.scrollTop;
        elm.scrollIntoView(true);
        destScroll = de.scrollTop;
        de.scrollTop = currentScroll;
        $(de).animate({scrollTop:destScroll}, 1000);
        panelOpen = false;
      });
  }else{
    currentScroll = de.scrollTop;
    elm.scrollIntoView(true);
    destScroll = de.scrollTop;
    de.scrollTop = currentScroll;
    $(de).animate({scrollTop:destScroll}, 1000);
  };
});

However, what you will also need to do is make sure your de element points to the right element - either html or body depending on the browser - for this you can use this:

var de;

/// calculate which element is the scroller element
$('body, html').each(function(){
  if ( this.scrollHeight > this.offsetHeight ) {
    de = this;
    return false;
  }
});

alert( $(de).is('body') ) /// will be true for Chrome, false for Firefox.

You will need to use this code in place of the following code:

var de = document.documentElement ? document.documentElement : document.body;

The reason for changing the code you were using is as follows:

/// store the current scroll position from the de element
currentScroll = de.scrollTop;
/// get the browser to do the scrollTo calculation
elm.scrollIntoView(true);
/// store where the browser scrolled to behind the scenes
destScroll = de.scrollTop;
/// reset our scroll position to where we were before scrollIntoView()
/// if you don't reset then the animation will happen instantaneously
/// because that is what scrollIntoView does.
de.scrollTop = currentScroll;
/// wrap the normal dom element de with jquery and then animate
$(de).animate({scrollTop:destScroll}, 1000);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top