Thursday 15 May 2014

how to correctly write plugins for jquery -


I need some tips on how to write correctly for jquery.

I started to study this question from the official website JQuery

and I write my own sticky header plug-in (I know that the internet I have just got the tasks needed to write the tasks.)

And so I wrote a simple task that works fine.

  Function StickyNave (L) {$ (. Window) .scroll (function () {if ($ (window) .scrollTop ()> gt0) ($ Height: '40px', lineHight: '40px'}, 200) {$ (LE). CSS ({status: 'fixed', top: '0px'}); $ (l) .stop ();} and {$ (L). CSS {Status: 'stable'}); $ (l) .stop (). Animate ({height: '80px', line hight: '80px'}, 200);}}); Stickynav ('neo');   

After trying to write the same function, but with the advice of the JQuery team.

  (function ($) {$ .fn Var $ window = $ (window) var scrolling = function () {$} {syn_query} = function (options) {settings = $ .extend ({TopSpacing: 0, initialHight: '80px', resHeight: '40px'}, option); var $ window = $ var scrolling = function Window.scroll (function () {if ($ window.scrollTop () & Gt; settings.topSpacing) {$ (this) .css ({status: 'fixed', top: '0px'}); $ (this) ({Height: settings.resHeight}, 200);} and {$ (It). Css ({status: 'static'}); $ (this) .stop (). ({Height: Settings.initialHeight}, 200);}});}; come back (scrolling); }}}) (JQuery); $ ('Neo') stickynav () .;   

And the result was a bit confusing, I did something wrong.

Please help and it is not difficult to interpret the changes.

I see that the big problem is that $ window.scroll Inside the function, you use this .
But this gives context to the window in that context ..

You have to store the reference of the nav element and instead It must be used . >

then the whole var should be scrolling = ...

  var scrolling = function () {var self = $ (this) ; $ Window.scroll (function () {if ($ window.scrollTop ()> settings.topSpacing) {self.css ({position: 'fixed', top: '0px'}); self.animate ({height : Settings.resHeight}, 200);} and {self.css ({status: 'static'}); itself. ({Height: settings.initialHeight}, 200);}}); };   

An additional correction will be to store the current status of the fixed NAV, so do not do animation on each scroll, but when you want to change the state.

Demo code

  var scrolling = function () {var self = $ (this); Data for itself ('Stickystadt', incorrect); $ Window.scroll (function () {var state = self data ('stickyState'), shouldBeFixed = $ window.scrollTop ()> settings.topSpacing; if (! State & amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; } {Self.cata} ({status: 'fixed', top: '0 pixels'}). ({Height: settings.resHeight}, 200); self.data ('stickyState', true);} and if ( State & amp; amp; amp; amp;; BeFixed!) {Self.css ({status: 'Stable'}) Animate ({height: settings.initialHeight}, 200); Data themselves ('StickyStart', False);}}); };    

No comments:

Post a Comment