First of all, I did not write this code. I found it on another site, and I want to study on it, having tried it myself. However, I cannot get it to work. I was looking for code for code if it is a jQuery plugin that is freely available or something else, but I cannot find it anywhere on the Internet.
I have a sidebar (with id #sidebar) and gave it a sticky class, I turned on jQuery at the top of the page, and I put this code in place in my head:
<script type="text/javascript">
var Sticky = function( $obj, opts ){
$(window).scroll(
function(e){
Sticky.onScroll(e, $obj, opts );
});
}
Sticky.onScroll = function( e, $o, opts ){
var iScrollTop = $(window).scrollTop();
var sClass = "sticky";
if( !$o.data(sClass) ){
$o.data(sClass, {css:{position:$o.css('position'),top:$o.css('top')}, offset:$o.offset()} );
}
var oOrig = $o.data(sClass);
var bIsSticky = $o.hasClass(sClass);
if( iScrollTop > oOrig.offset.top && !bIsSticky ){
$o.css({position:'fixed',top:0}).addClass(sClass);
}else if(iScrollTop < oOrig.offset.top && bIsSticky){
$o.css(oOrig.css).removeClass(sClass);
}
}
Sticky( $('#sidebar') );
</script>
As you can see, the last line of JS is Sticky( $('#sidebar') );fired on the #sidebar element. However, when scrolling down, this error is written to the Chrome log:
Uncaught TypeError: Unable to read the "offset" of the undefined property
Firebug is a bit more verbose and says:
oOrig undefined: if( iScrollTop >
oOrig.offset.top && !bIsSticky ){
, - , ?
!