Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an element visible only when scrolled down to ***px

Tags:

jquery

I am using a Scroll to top button on my website. I am using this Jquery for it

    $(window).scroll(function() {
    if ($(this).scrollTop()) {
        $('#cttm:hidden').stop(true, true).fadeIn();
    } else {
        $('#cttm').stop(true, true).fadeOut();
    }
});


  $(document).ready(function(){
      var bottom = ($(window).outerHeight() - $(window).height()) - 150; // 150 pixel to the bottom of the page; 
      $(window).scroll(function(){
          if ($(window).scrollTop() >= bottom ) {
                  $("#cttm").fadeTo("slow",.95);
             } else {
                  $("#cttm").fadeOut("slow");
             }
      });

      $("#cttm").click(function(){
          $('html, body').animate({scrollTop:0}, 'slow');
          $("#cttm").fadeOut("slow");
      });
  });

This Jquery works great but i want the element to appear only when we scroll to 200px from the top or something like that. Is there any way to do it with JQuery ?

like image 802
Deepak Kamat Avatar asked Jul 05 '12 08:07

Deepak Kamat


1 Answers

You don't need the window height to do that.

var isVisible = false;
$(window).scroll(function(){
     var shouldBeVisible = $(window).scrollTop()>200;
     if (shouldBeVisible && !isVisible) {
          isVisible = true;
          $('#mybutton').show();
     } else if (isVisible && !shouldBeVisible) {
          isVisible = false;
          $('#mybutton').hide();
    }
});

Demonstration : http://jsfiddle.net/dystroy/gXSLE/

like image 148
Denys Séguret Avatar answered Nov 15 '22 13:11

Denys Séguret