Help with Sticky that appears after scrolling x amount

I’m new to using sticky’s so I have no clue how to due this. I found some examples at http://stickyjs.com and have them working as is, but I can’t figure out how to customize it to work on my site.

here is a link to a site that is doing what I’m trying to do:
http://www.thumbtack.com

Here is a link to the page I’m trying to get it to work on:
http://aaronhaas.com/bsi2/index.html

If you looking at the site I’m trying to have the blue sticky start out invisible and appear after the user scrolls down past the banner at the top and then stick just below the nav bar.

i want it to look like this after the user scrolls

I have this in my head tags:


<script type="text/javascript" src="js/jquery.sticky.js"></script>
  <script>
    $(window).load(function(){
      $("#cta-sticky").sticky({ topSpacing: 100 });
    });
  </script>

here is the sticky div:


<!-- sticky-->
<div id="cta-sticky">
    <form class="form-inline center" role="form">
    <h4 class="cta-title">This is the sticky</h4>
      <div class="form-group">
        <label class="sr-only" for="">Zip Code</label>
        <input type="text" class="form-control" id="zip" placeholder="Zip Code">
      </div>

      <button type="submit" class="btn btn-orange">Get Quote</button>
    </form>
</div>

here is the query sticky file:


// Sticky Plugin v1.0.0 for jQuery
// =============
// Author: Anthony Garand
// Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
// Improvements by Leonardo C. Daronco (daronco)
// Created: 2/14/2011
// Date: 2/12/2012
// Website: http://labs.anthonygarand.com/sticky
// Description: Makes an element on the page stick on the screen as you scroll
//       It will only set the 'top' and 'position' of your element, you
//       might need to adjust the width in some cases.

(function($) {
  var defaults = {
      topSpacing: 0,
      bottomSpacing: 0,
      className: 'is-sticky',
      wrapperClassName: 'sticky-wrapper',
      center: false,
      getWidthFrom: ''
    },
    $window = $(window),
    $document = $(document),
    sticked = [],
    windowHeight = $window.height(),
    scroller = function() {
      var scrollTop = $window.scrollTop(),
        documentHeight = $document.height(),
        dwh = documentHeight - windowHeight,
        extra = (scrollTop > dwh) ? dwh - scrollTop : 0;

      for (var i = 0; i < sticked.length; i++) {
        var s = sticked[i],
          elementTop = s.stickyWrapper.offset().top,
          etse = elementTop - s.topSpacing - extra;

        if (scrollTop <= etse) {
          if (s.currentTop !== null) {
            s.stickyElement
              .css('position', '')
              .css('top', '');
            s.stickyElement.parent().removeClass(s.className);
            s.currentTop = null;
          }
        }
        else {
          var newTop = documentHeight - s.stickyElement.outerHeight()
            - s.topSpacing - s.bottomSpacing - scrollTop - extra;
          if (newTop < 0) {
            newTop = newTop + s.topSpacing;
          } else {
            newTop = s.topSpacing;
          }
          if (s.currentTop != newTop) {
            s.stickyElement
              .css('position', 'fixed')
              .css('top', newTop);

            if (typeof s.getWidthFrom !== 'undefined') {
              s.stickyElement.css('width', $(s.getWidthFrom).width());
            }

            s.stickyElement.parent().addClass(s.className);
            s.currentTop = newTop;
          }
        }
      }
    },
    resizer = function() {
      windowHeight = $window.height();
    },
    methods = {
      init: function(options) {
        var o = $.extend(defaults, options);
        return this.each(function() {
          var stickyElement = $(this);

          var stickyId = stickyElement.attr('id');
          var wrapper = $('<div></div>')
            .attr('id', stickyId + '-sticky-wrapper')
            .addClass(o.wrapperClassName);
          stickyElement.wrapAll(wrapper);

          if (o.center) {
            stickyElement.parent().css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"});
          }

          if (stickyElement.css("float") == "right") {
            stickyElement.css({"float":"none"}).parent().css({"float":"right"});
          }

          var stickyWrapper = stickyElement.parent();
          stickyWrapper.css('height', stickyElement.outerHeight());
          sticked.push({
            topSpacing: o.topSpacing,
            bottomSpacing: o.bottomSpacing,
            stickyElement: stickyElement,
            currentTop: null,
            stickyWrapper: stickyWrapper,
            className: o.className,
            getWidthFrom: o.getWidthFrom
          });
        });
      },
      update: scroller,
      unstick: function(options) {
        return this.each(function() {
          var unstickyElement = $(this);

          removeIdx = -1;
          for (var i = 0; i < sticked.length; i++)
          {
            if (sticked[i].stickyElement.get(0) == unstickyElement.get(0))
            {
                removeIdx = i;
            }
          }
          if(removeIdx != -1)
          {
            sticked.splice(removeIdx,1);
            unstickyElement.unwrap();
            unstickyElement.removeAttr('style');
          }
        });
      }
    };

  // should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
  if (window.addEventListener) {
    window.addEventListener('scroll', scroller, false);
    window.addEventListener('resize', resizer, false);
  } else if (window.attachEvent) {
    window.attachEvent('onscroll', scroller);
    window.attachEvent('onresize', resizer);
  }

  $.fn.sticky = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.sticky');
    }
  };

  $.fn.unstick = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method ) {
      return methods.unstick.apply( this, arguments );
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.sticky');
    }

  };
  $(function() {
    setTimeout(scroller, 0);
  });
})(jQuery);


any help would be greatly appreciated

Hi,

You are including jQuery twice - once on line 29:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

and once on line 368:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Delete the first occurrence, then move the second occurrence to the head of your document (or better still - gather all of your scripts before the closing </body> tag) and all will work as expected :slight_smile:

Thanks again pullo that fixed it.

Any ideas on how to make it appear after it scrolls a curtain amount of pixels? I thought about using display: none; for the default, but how would I make it appear after the user scrolls down?

I found this script, but i think it needs to be tweaked a bit to do exactly what I need:


$(window).scroll(function() {
    if ($(this).scrollTop() == 75) {
        $("#cta-sticky").hide();
    }
    else {
        $("#cta-sticky").show();
    }

I would set the initial display property to none (as you have done), then fade it in when the user has scrolled a certain amount of pixels.
You can determine this using the .scroll() and .scrollTop() functions:

$(window).scroll(function() {
  // use the value from $(window).scrollTop(); 
});

http://api.jquery.com/scroll/
http://api.jquery.com/scrollTop/

Then you should check if the element is visible before attempting to show it. You example would fire every time the user scrolled, when essentially you only need to have it fire once.

HTH

I played around with a few things but I’m not really sure how to do it, especially the syntax

For the first part of just getting it to appear after they scroll down 100px I tried this:


function showSticky(){  
  $(window).scrollTop(100).$('#cta-sticky').show();       
} 

but it’s not working. I’m sorry, but I’m really bad with jquery

no jquery

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title></title>
<style type="text/css">
/*<![CDATA[*/

#nav {
  position:fixed;overflow:hidden;left:0px;top:0px;width:100%;height:50px;background-Color:blue;
}

#sticky {
  position:fixed;overflow:hidden;left:0px;top:50px;width:100%;height:100px;
}

.sticky {
  position:absolute;left:0px;top:0px;width:100%;height:100px;background-Color:red;
}

#stickyB {
  position:fixed;overflow:hidden;left:0px;bottom:0px;width:100%;height:50px;
}

.stickyB {
  position:absolute;left:0px;bottom:0px;width:100%;height:50px;background-Color:#FFFFCC;
}

/*]]>*/
</style></head>

<body>
<div id="nav" >
</div>
<div id="sticky" >
 <div class="sticky">sticky html</div>
</div>

<div id="stickyB" >
 <div class="stickyB">sticky html</div>
</div>

 <div style="height:2000px;"></div>



<script type="text/javascript">
/*<![CDATA[*/

function zxcScrollSticky(o){
 var id=o.StickyID,ms=o.Animate,oa=o.OpenAt,p=document.getElementById(id),c=p?p.getElementsByTagName('DIV')[0]:null;
 if (c){
  o=this;
  o.id=id;
  o.a=[p,'height',c.offsetHeight,0];
  o.oa=typeof(oa)=='number'&&oa>0?oa:0;
  o.ms=typeof(ms)=='number'&&ms>20?ms:500;
  this.addevt(window,'scroll','scroll');
  o.scroll();
 }
}

zxcScrollSticky.prototype={

 scroll:function(){
  var o=this;
  var ud=(window.innerHeight?window.pageYOffset:document.documentElement.clientHeight?document.documentElement.scrollTop:document.body.scrollTop)>o.oa,t=ud?o.a[2]:0;
  if (ud!=o.ud){
   o.animate(o.a,o.a[3],t,new Date(),o.ms*Math.abs((t-o.a[3])/o.a[2]));
  }
  o.ud=ud;
 },

 animate:function(a,f,t,srt,mS){
  clearTimeout(a[4]);
  var oop=this,ms=new Date()-srt,n=(t-f)/mS*ms+f;
  if (isFinite(n)){
   a[3]=Math.max(f<0||t<0?n:0,n);
   a[0].style[a[1]]=a[3]+'px';
  }
  if (ms<mS){
   a[4]=setTimeout(function(){ oop.animate(a,f,t,srt,mS); },10);
  }
  else {
   a[3]=t;
   a[0].style[a[1]]=t+'px';
  }
 },

 addevt:function(o,t,f,p,p1){
  var oop=this;
  o.addEventListener?o.addEventListener(t,function(e){ return oop[f](p,p1);},false):o.attachEvent?o.attachEvent('on'+t,function(e){ return oop[f](p,p1); }):null;
 }

}


new zxcScrollSticky({
 StickyID:'sticky',  // the unique ID name of the sticky parent DIV.      (string)
 OpenAt:50,          //(optional) the scroll position to open the sticky. (number, default = 0)
 Animate:500         //(optional) the animation dutation in millisec.     (number, default = 1000)
});

new zxcScrollSticky({
 StickyID:'stickyB'
});
/*]]>*/
</script>

</body>

</html>

thanks guys that got it working perfect!!!