javascript - jQuery Sticky Sidebar failing -


First of all I did not write this code. I found it on someone else's website and i want to learn it from myself trying it out though i can not work it i have googled for code if it is a jQuery plugin that is freely Is available or anything, but I can not find it anywhere on the web.

I have given it a "sticky" class (with Sidebar ID # sidebar), I have included jQuery at the top of the page, and I have placed this code in the head:

< Pre> & lt ;! - Floating Sidebar JQuery - & gt; & Lt; Script type = "text / javascript" & gt; Var sticky = function ($ obj, opts) {$ (. Window) .scroll (function (e) {sticky .oncroll (e, $ obj, opts);}); } Sticky.onecroll = function (e, $ o, ops) {var iScrollTop = $ (window) .scrollTop (); Var sClass = "sticky"; // Set Original Data (! $ O.data (sClass)) {$ o.data (sClass, {css: {status: $ o.css ('condition'), top: $ o.css ('top ')}, Offset: $ o.offset ()}); } Var oOrig = $ o.data (sClass); Var bIsSticky = $ o.hasClass (sClass); If (iScrollTop & gt; orig.offset.top & BIsSticky) {$ o.css ({status: 'fixed', top: 0}). AddClass (sClass); } And if (iScrollTop & lt; oOrig.offset.top & bIsSticky) {$ o.css (oOrig.css) .removeClass (sClass); }} Sticky ($ ('# sidebar')); & Lt; / Script & gt;

As you can see, the last JS line sticky ($ ('# sidebar')); However, when you scroll down, this error is written on the log of Chrome:

Unkit type error: undefined property 'offset' Can not read

Firebug is a bit and verbose, and says:

oOrig is undefined: if (iScrollTop> oOrig .offset.top & amp; amp ;! BIsSticky) {I am trying to understand this but someone helps me by looking at why it does not work Tax Used to be?

Thank you!

Jack

Wow, new answer ... Thanks Felix

Wrap the function call in the finished function.

  $ (function () {sticky ($ ('# sidebar'))});  

When you call sticky ($ ('# sidebar'), the probability of not getting a dome is most likely, so when the data is set to does not do anything realistic:

  $ o.data (sClass, {css: {status: $ o.css (' Position '), top: $ o CSS (' top ')} Offset: $ o.offset ()};]  

So when it gets data on line:

  var oOrig = $ o.data (sClass);  

This can not actually get the data.

Ace That's because DOM is not ready to manipulate elements because DOM is not ready yet.

H2> Old Answer (Not Right!)

$ Offset is a Function .

Problem in this line:

  if (iScrollTop> OOrig.offset.top & BIsSticky) {  

It is: oOrig.offset is a function, is not a variable, then oOrig.offset.top is not valid. Just call the function and it with the top property A variable will return that you have access Can and are:

  if (iScrollTop & gt; Oreg.offset () Top & amp; Amp; Amp;!! BIsSticky) { 

Interpretation:

function is the reference (function in jquery).

You must call the function to access the .top property.


Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -