A few jQuery tricks from a newb
Hi all, this is your newb web developer talking again. While some of the following might be obvious to the more experienced web devs among you, this is a post that I wish I’d read when I just started using jQuery.
Write your own jQuery plugins
The word “plugin” usually entails something complicated and with some non-trivial learning curve (e.g. how many of you ever wrote a Chrome of Firefox plugin?) Well, in jQuery, this is really not the case. Here is how you write a simple jQuery plugin:
$.fn.enable = function() { $(this).prop("disabled", false); }; $.fn.disable = function() { $(this).prop("disabled", true); }; |
I find it useful to wrap even simple one liners such as .prop(“disabled”, false) with a plugin, because the semantics of writing $(“#foo”).disable() is much nicer than playing with properties/attributes directly. I haven’t written a lot of plugins yet, but it’s something to keep in mind as a useful tool to wrap actions on specific DOM elements.
Know the commonly used plugins
There are a ton … I still know very few of them. Here are a bunch of useful ones (and the ones I personally know and use).
A lot of plugins are very easy to use, and have good documentation and demos, so not using them and rolling your own solution is usually just a result of ignorance. Take the time to educate yourself!
UI Queues
For a long time I’ve that you can do things like $(“#mydiv”).show(), $(“#mydiv”).hide() and even $(“#mydiv”).show(1000) for a simple animation. Only recently I discovered you can actually chain these using Event Queues:
$("#mydiv") .hide(1000) .delay(500) .show(200) .fadeOut(); |
Each call to an animation method gets queued up and executes after the previous one.
Deferred
jQuery Deferred is a little gem. It lets you write fluent code similar to the queue example above. Here is how you use it:
$.when($.post('http://api.com/request_1'), $.post('http://api.com/request_2')) .then(function(){alert("Got two responses")}); |
You can also use them with the event queue:
$("#mydiv") .show(1000) .delay(500) .promise() .then(function(){/*do something */}); |
That’s all I have for now. Have any essential tips & tricks that I’m missing out on?