Javascript Question

how to attach scroll event to window after scroll animation

I'm trying to display a div after scroll animation has finished and hide it when I scroll up/down the page. This is my attempt:

$('#cta').on('click', function(e) {
e.preventDefault();
$('#layer, #servicesContent').addClass('active');

var position = parseInt($('#services').offset().top);
$('html, body').animate({
scrollTop: position - 100
}, 'slow', function() {
$(window).bind('scroll', function() {
$('#layer, #servicesContent').removeClass('active');
});
});
});


it doesn't work. the active class is removed after animation has finished and not with scroll movement.

Any idea?

Thanks in advance

Answer

Not exactly sure why, but apparently it takes the window somewhere around 20 milliseconds to exit the scroll state, at least on Chrome, on Windows. Or it might be a jQuery trick to fire the animation function 20ms sooner, so it feels more natural. (Human eye and mind make connections that take tiny amounts of time and maybe they took it into account).

Anyway, in order to make sure you bind after the scroll has ended, give it a full 100ms to finish and bind afterwards:

$('#cta').on('click', function(e) {
  e.preventDefault();
  $('#layer, #servicesContent').addClass('active');

  var position = 120;
  $('html, body').animate({
    scrollTop: position - 100
  }, 'slow', function() {
    setTimeout(function(){
      $(window).bind('scroll', function() {
        $('#layer, #servicesContent').removeClass('active');
      });
    },100)
  });
});

working fiddle.

Please note I had hard-coded a value to position, as #services is not defined in my example.

Also please note that hiding events on scroll is a really bad idea in terms of usability. Users might want to scroll so they view the div better or read it in full, but they will end up hiding it, which would be annoying. I would at least check the scroll event for a minimum velocity or distance in order to hide an element from the screen.

Comments