jQuery.quickEach
With jQuery, when you need to iterate all elements with a specific class for example, you use the each()
method and inside the callback function you must convert the DOM element you receive as this
to a jQuery object in order to access it's jQuery specific methods: $(this)
This is not such a big issue but if you have a lot of items and/or do this often, then times ads up. It would be a blast to have the this
object directly as a jQuery instance. So here's a $ little plugin that does exactly that
Source website:
http://jsperf.com/jquery-each-vs-quickeach
The code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | jQuery.fn.quickEach = (function() { var jq = jQuery([1]); return function(c) { var i = -1, el, len = this.length; try { while (++i < len && (el = jq[0] = this[i]) && c.call(jq, i, el) !== false); } catch (e) { delete jq[0]; throw e; } delete jq[0]; return this; }; }()); |
If you run the test on that page, on most browsers you'll see that quickEach() is about 80% faster than native each()
On typing finished jQuery plugin
If you are developing a form and you require certain validations; check if username is available or not for example - the way to do that is to listen for the change/focusout DOM events. You can also check it on every keypress but if the validation does some expensive checking in the background that is out of the question. So here is a really small jQuery plugin that does tell you when a user finished typing inside a text box. The way it does it is to compute the speed the user is typing with and when a delay longer than twice the speed average occurs, the event is triggered and your validation function is called. Simple enough.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $(document).ready(function () { $.fn.onTypeFinished = function(func) { var T = undefined, S = 0, D = 1000; $(this).bind("keypress", onKeyPress).bind("focusout", onTimeOut); function onKeyPress() { clearTimeout(T); if (S == 0) { S = new Date().getTime(); D = 1000; T = setTimeout(onTimeOut, 1000); return; } var t = new Date().getTime(); D = (D + (t - S)) / 2; S = t; T = setTimeout(onTimeOut, D * 2); } function onTimeOut() { func.apply(); S = 0; } return this; }; }); |
The way to use it:
1 | $("input[name='username']").onTypeFinished(myValidationFunction) |
And here is a small demo: