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
Wow, new answer…Thanks felix
wrap the function call in a ready function.
The dom is most likely not ready when you call
Sticky($('#sidebar'))so when .data is used to set data on$oit actual does nothing:So when it gets the data on line:
it cannot actualy get the data.
This is because the dom elements are not ready to be manipulated because the dom is not ready yet.
OLD ANSWER (NOT RIGHT!)
$.offset is a function.
The problem in the line:
is that:
oOrig.offsetis a function, not a variable. SooOrig.offset.topis not valid. Simply call the function and it will return a variable with the top property which you can access:Explination:
oOrig.offsetis a reference to a function (the offset function in jquery).You must call the function to access the
.topproperty.