1

My problem

I am making a vertical website for a client who wishes to have the window "snap" to the nearest page when most of the element is visible in the viewport. So, if the page is 85% visible, it should scroll to be 100% visible.

My problem is that occasionally when scrolling all the way to the top or bottom of the viewport, the viewport will "stick" to the first or last element, preventing a few scroll events and causing a highly noticeable flicker.

A working fiddle is here: http://jsfiddle.net/RTzu8/1/ To reproduce the error, use the scrollbar to scroll to the bottom of the page. Then, scroll up with your mousewheel. You should see the flicker. Sometimes it takes a few refreshes or attempts, but the issue is highly reproducible.

I'm at a loss as to what could be causing this issue. See below for a run-down of my code and what I have tried to prevent it so far.


My code

To accomplish my snapping, I needed to detect whether an element was a certain percentage visible. So, I added a jQuery function, isNearScreen, below. I have thoroughly tested this function, and as far as I can tell it returns accurate results.

//Modification of http://upshots.org/javascript/jquery-test-if-element-is-in-viewport-visible-on-screen 
//Returns "true" if element is percent visible within the viewport
$.fn.isNearScreen = function(percent){

    var offset = 1 - percent;

    var win = $(window);

    var viewport = {
        top : win.scrollTop()
    };

    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    bounds.bottom = bounds.top + this.outerHeight();
    bounds.top = bounds.top;

    //If the element is visible
    if(!(viewport.bottom < bounds.top || viewport.top > bounds.bottom)){

        //Get the percentage of the element that's visible
        var percentage = (viewport.bottom - bounds.top) / this.height();

        //If it's greater than percent, but less than 1 + (1 - percent), return true;
        return (percentage > (1 - offset) && percentage < (1 + offset));
    }
    return false;

};

I then created a snap function, which makes use of Underscore.js's _.debounce function, to only fire on the trailing end of continuous scroll events. It fires after a 500ms timeout, and I am fairly (though not 100%) convinced that it is firing correctly. I have not been able to reproduce console logs that would indicate multiple concurrent firings.

//Snaps the screen to a page after scroll input has stopped arriving.
var snap = _.debounce(function(event){

    //Check each page view            
    $.each($('.page-contents'), function(index, element){

        //If the page view is 70% of the screen and we are allowed to snap, snap into view
        if($(element).isNearScreen(0.7)){

            $('html,body').animate({
                scrollTop: $(element).offset().top
            }, 300);

        }
    });  
}, 500);

Finally, I bind to the window's scroll event

$(window).on('scroll', snap});

The (extremely simplified) HTML:

<div class="page">
     <div class="page-contents"></div>
 </div>
 <div class="page">
     <div class="page-contents"></div>
 </div>
 <div class="page">
     <div class="page-contents"></div>
 </div>
 <div class="page">
     <div class="page-contents"></div>
 </div>

and CSS:

.page{
    height: 750px;
    width: 100%;
    margin: 10px 0;
    background: gray;
}

.page-contents{
    height: 100%;
    width: 100%;
}

What I've tried

I have tried the following, with no success:

  • Setting a boolean, 'preventSnap', on the window, checking its state, and only firing the animate portion of snap if it is set to false. After animation, set it to true, then set it to false after 500ms (which should in theory prevent double firings).
  • Calling .stop() on the element before running the snap animation.
  • Calling event.preventDefault() on the scroll event before running the animation.
  • Reducing and increasing my _.debounce delay. Interestingly, a lower _.debounce delay (200-300ms) seems to aggravate the problem and a higher _.debounce delay (1000ms) seems to fix it. This is not an acceptable solution, however, as it feels "long" waiting 1sec for the page to "snap".
  • Changing the heights of the elements

If there is any other information I can provide, please let me know. I'm at a loss!

1
  • Try decreasing the duration, i think it's related to the rendering of the browser(s). I've had the same problem.
    – Jack
    Commented Dec 10, 2013 at 1:09

1 Answer 1

1

I think this is a combination of events and how _.debounce works. I noticed in the fiddle (in Chrome) that the elements were 'jitterring' long after the snap finished. If you put a console log in the snap event handler you can see it's constantly being called after a snap even with no scroll inputs.

This must be the scroll animation itself setting off the snap, I tried to set a flag to prevent dual snapping and clearing the flag after the animation was finished -- however that didn't work I think because _.debounce is queuing the event to happen later (after the animation finishes and clears the flag).

So what does work is to add this as the start of the snap handler:

var nosnap = false;

var snap = _.debounce(function(event){

    // Don't snap if already animating ...
    if (nosnap) { nosnap = false; return; } 
    nosnap = true;

Fiddle

That prevents the animation directly firing the next snap event -- however that's going to cause issues if you scroll again during the animation.

So, that's a bit of a hack. Ideally you want to be able to tell what's causing the scroll event and react accordingly but there's no easy way to do that.

I absolutely think you need to stop the animation when handling a second scroll event as well.

2
  • You are right about the scroll firing the snap. jQuery scrollTop fires a scroll event. I'm currently using a combination of the above solution, with a slight modification. Instead of immediately setting nosnap=false, I set it in a timeout. I also set an event.preventDefault for a timeout duration of the animation length - you are prevented from scrolling while it's animating, and you are prevented from snapping for the delay on a _.debounce. It's quite hacky, but it seems to be doing the trick. I also call .stop() before I begin the animation. Fiddle here: jsfiddle.net/RTzu8/33
    – Tom Lagier
    Commented Dec 10, 2013 at 19:25
  • Cool, glad you found something that works. I'm still curious about the right way to do it, i.e. detecting what fired each scroll event ... maybe someone else will have an answer for that, or maybe I'll do some more research and ask a different question later.
    – SpaceDog
    Commented Dec 10, 2013 at 23:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.