Apr
2012
JS/jQuery Code Snippets
Some common Javascript snippets I use in my projects. If you got something useful, please share in comments section.
-
Check if element has scrollbar
I was working on a project where I need to add jQuery UI resizable to a list but I have to check if it has a scrollbar. I endup with a tiny jQuery plugin
(function($) { $.fn.hasScrollBar = function() { return this.get(0).scrollHeight > this.height(); } })(jQuery);Usage
Some long text... -
setInterval and setTimeout
Whenever you use setInterval make sure you clear it just incase if never gets cleared.
var timer = setInterval(function(){ if(someConditionIsTrue){ clearTimeout(timer); } },100); /*But if, due to some reasons, the 'someCondition' never gets true than you need to clear the timer otherwise it might turn into an infinite loop*/ setTimeout("clearTimeout(timer)",10000) //10 seconds or more -
Strip out duplicate items in an Array
//Pure javascript Array.prototype.copyUnique = function removeDuplicateElement() { var newArray=new Array(), arrayName=this; label : for(var i=0; i < arrayName.length; i++ ) { for(var j=0; j < newArray.length;j++ ) { if(newArray[j]==arrayName[i]) continue label; } newArray[newArray.length] = arrayName[i]; } return newArray; } //Based on jQuery Array.prototype.copyUnique = function(original) { var a = jQuery(original); return jQuery.makeArray(a.filter(function(i, item) { return i === jQuery.inArray(item, a); })); }Usage
[1,2,3,3,4,3,4,5].copyUnique(); // return [1, 2, 3, 4, 5]
-
Check if a value is in an Array
//jQuery version jQuery.inArray("value", arr); // Usage: if( jQuery.inArray("value", arr) != -1 ) { true }; //Javascript version Array.prototype.inArray = function (value) { var i; for (i=0; i < this.length; i++) { if (this[i] === value) { return true; } } return false; }; //[1,2,3].inArray(2) > true //[1,2,3].inArray(22) > false







