Hi folks,
First of all I did not write this code. I found it on somebody else's website and I want to learn from it by trying it out myself. However I can't make it work. I've googled for the code in case it's a jQuery plugin that's freely available or anything, but I can't find it anywhere on the web.
I have my sidebar (with id #sidebar) and have given it the class "sticky", I've included jQuery at the top of the page, and I've put this code in place in the head:
<!-- Floating sidebar jQuery -->
<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";
//set original data
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 final JS line Sticky( $('#sidebar') );
fires on the #sidebar element. However, when you scroll down, this error is written to Chrome's log:
Uncaught TypeError: Cannot read property 'offset' of undefined
Firebug is a bit more verbose, and says:
oOrig is undefined:
if( iScrollTop > oOrig.offset.top && !bIsSticky ){
I'm trying my best to understand this but can somebody help me see why it's not working?
Thanks!
Jack