Codexy
Codexy

Reputation: 81

jQuery scrollTop() problems

i'm trying to achieve this: qhen button is clicked, html is animated down to the "welcome" section and only then the overflow-y is visible (so that you can't scroll down from the header if not pressing the button). (That's the first script). But i'm having problems with the second script. Basically is scrolls and fix the document at height 0px and can't scroll down. What i'm trying to achieve here is that if you scroll back from the welcome section, the html is animated up to the top of the page (returning everything at the initial state).

$(window).ready(function() {

    $(".scroll-icon").click(function() {

        $('html, body').animate({
            scrollTop: $("#welcome").offset().top
        }, 2000); 

        $("html").delay(200).queue(function (next) { 
            $(this).css({
                'overflow-y': 'visible'
            }); 
            next(); 
          });
    }); 

    $(window).scroll(function() {

        var distance = $("#welcome").offset().top

          if ($(document).scrollTop() < distance) {
             $('html, body').animate({
                 scrollTop: $("#header").offset().top
             }, 2000);
          } 
    });


});

Here's a JsFiddle showing my problem: https://jsfiddle.net/kp2yqyo8/6/

Thanks to all :)

Upvotes: 1

Views: 858

Answers (1)

Jeancarlo Fontalvo
Jeancarlo Fontalvo

Reputation: 128

well I tried this:

// 1. Use a flag to check when you're welcome to the party!.
window.ImWelcome = false;

// 2. Your event click handler -- Same
$(".scroll-icon").click(function() {

    $('html, body').animate({
        scrollTop: $("#welcome").offset().top
    }, 2000); 

});  

// 3. Scroll handler...
$(window).scroll(function() {

    // 3.1 Store the values 
    var distance  = $("#welcome").offset().top
    var scrollTop = $(document).scrollTop();

    // 3.2 So..? Did you arrive to the party already ?
      if(scrollTop == distance){
        window.ImWelcome = true; // 3.2.1 Oh Yeah! 
      }

      // 3.3 Hmmm ... Seems like you want to leave huh? Ok let me take you to home
      if ($(document).scrollTop() < distance && window.ImWelcome) {
         $('html, body').animate({
             scrollTop: $("#header").offset().top
         }, 2000);

         // Oh You're home and not welcomed 
         window.ImWelcome = false;
      } 

});

Now, talking seriously, the flag approach is simple. This used a global variable because it has to keep the state in the flag.

JsFiddle here!

Upvotes: 1

Related Questions