Top 10 custom JavaScript functions of all time
UPDATE: For anyone who lands on this article months after the fact
, there is now a podcast entry about this article reviewing each and every function.
If there was ever a universal common.js shared among the entire develosphere, you’d fine these ten (plus one bonus) functions. It would be the swiss army knife no developer would go into production without. They have no doubt been tested tried and true and have proven usefulness and helpfulness to all those who’ve used them. So without further ado, here are what I believe to the top ten greatest custom JavaScript functions in use today.
Upon further reading this article, it is suggested that for this article in particular the reader should use an alternate style with cleaner whitespace and larger margins. This is available by selecting Clean with Whitespace available on the side bar.
10) addEvent()
Surely a staple to event attachment! Regardless to what version you use written by whatever developer, it does what it says it does. And of course as you might of known, I’ve put together quite a handy version myself recently of addEvent() with some help from the contest winner and Mark Wubben along with a few minor syntax adjustments. But just to be fair to Scott Andrew, here is the original that started it all.
Scott Andrew’s original addEvent() function
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
9) addLoadEvent()
Originally written by Simon Willison and highly adopted by many others as a simple way to add events to trigger after the page has loaded. This of course attaches all your events to the onload event handler which some still see as necessary, nevertheless it does exactly what it’s supposed to, and does it well.
addLoadEvent() by Simon Willison
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}
else {
window.onload = function() {
oldonload();
func();
}
}
}
Of course another method is to simply assign multiple event listeners to the window by using addEvent() as described in number 10 as follows:
assigning multiple load events to window
addEvent(window,'load',func1,false);
addEvent(window,'load',func2,false);
addEvent(window,'load',func3,false);
8) getElementsByClass()
Originially written by nobody in particular. Several developers have implemented their own version and no one single version has proven to be better than another. As you might expect, my humble self has even had a crack at it. This function was spawned from developers needing a quick and elegant way of grabbing elements by a className and to a developer’s surprise, it’s not an original DOM method as one might think…afterall, we have getElementById, getElementsByName(), getElementsByTagName, what the hell happened to getElementsByClass??? Here it is in all its glory:
getElementsByClass by Dustin Diaz
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!
7) cssQuery()
Originally written by Dean Edwards as a way to query the DOM according to CSS properties which supports a multitude of selectors. However in all fairness, this is more like a mini-library and not quite so light on the weight factor, but still, a very kick-ass function. Due to its length (and CC lisencing) I won’t post it on this site. Full documentation can be found on the myCssQuery reference and download page.
6) toggle()
To be totally honest, there are probably more variations of this function than there needs to be. The history of ‘toggling’ basically comes down to showing/hiding an element upon an event being fired. To make matters much simpler, I too have put one together. But by no means is it considered the ultimate toggle function, but it does do the basic functionality of showing and hiding.
toggle() by the masses
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'none' ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
}
5) insertAfter()
As far as I know, Jeremy Keith sort of came up with this idea even though one would have thought this too would be a DOM core method. But just like getElementsByClass, it isn’t. So rather than pulling the function straight out of the book, I’ll leave that up to you to buy it yourself. Instead I’ve pulled this simple method from public domain:
insertAfter() on public domain
function insertAfter(parent, node, referenceNode) {
parent.insertBefore(node, referenceNode.nextSibling);
}
4) inArray()
This too is very sad that this isn’t part of the DOM core functionality. But hey, it makes for fun references like this! This function however isn’t quite a function; it’s a prototype that extends the DOM Array object. I remember one day thinking to myself “surely I can do this in PHP, it’s gotta be in JavaScript.” Well, this extension makes it work just like you’d expect if you’re a PHP developer. Here is a version from EmbiMEDIA
inArray Prototype Array object by EmbiMedia
Array.prototype.inArray = function (value) {
var i;
for (i=0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
3, 2, & 1) getCookie(), setCookie(), deleteCookie()
I honestly don’t know what I would do without these guys. I hate the DOM implementations of setting cookies in JavaScript. In PHP it’s so easy, and it’s easy for one main reason, they work just like the functions below. All three of these functions were found to be public domain and free to use.
getCookie(), setCookie(), deleteCookie() open domain
function getCookie( name ) {
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ';', len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires ) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name+'='+escape( value ) +
( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
( ( path ) ? ';path=' + path : '' ) +
( ( domain ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );
}
function deleteCookie( name, path, domain ) {
if ( getCookie( name ) ) document.cookie = name + '=' +
( ( path ) ? ';path=' + path : '') +
( ( domain ) ? ';domain=' + domain : '' ) +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
Last but not least, a bonus function: The Prototype Dollar Function
This function straight up kicks so much ass. First of all, just look at it.
Prototype function $
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
// Sample Usage:
var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2');
function alertElements() {
var i;
var elements = $('a','b','c',obj1,obj2,'d','e');
for ( i=0;i
Tell me that’s not beautiful! Short not only by name, but by reference. It not only takes in strings, it takes objects too. You can pass it one argument, or pass it many! This by far is my favorite function of all time which will provide years and years of handiness.
And so will they all…
I hope this quick and handy list of JavaScript functions has been as useful for you as they have been for me. And for your downloading pleasure, here is all these functions wrapped up in a common.js just for you.
After the fact
Added after 30 comments or so…: Ok, I can understand everyone’s point of view when it comes to ‘these ten being the best‘. The fact of the matter is, this is what I think were the best. If Dean Edwards wrote his top ten, I’m sure it would be different. If Stuart Langridge wrote his list, it too would be different. I mainly concentrated my list on the DOM. Browser detection is up to the developer at hand. Ajax functions I felt do not qualify as an ‘all timer’ mainly because Ajax is still in its infancy and has yet to impress me with something amazingly useful. For those wishing to just push these functions aside and slap on prototype to their documents, go ahead and slap on the extra 30k if you feel that’s necessary. Nevertheless, thank you all thus far for the wonderful comments. I still hope this small list will come in handy for quite some time. And believe me, there are hundreds of other great functions that could possibly make it here. Just because it isn’t here, doesn’t mean it’s not good. Just use your imagination ;)













November 29th, 2005 at 9:30 pm
You’re right–they would definitly be found in “common.js”! I use half of those as you posted them, and have my own versions of most of the others.
A lot of those we have also written versions of together with the community over at CWM.
–Jim
November 29th, 2005 at 10:11 pm
I can’t say how many times I have, just as you said, though ‘well that must be a function since _______ is a function’. Thanks for a such a great list. I also like that you praised the elegance of the $ function.
November 30th, 2005 at 8:13 am
Nice entry!… my only question is, what is the $() function? I’m not sure if I understand what it is about… does it just stuff whatever (references to elements by String id) you pass it into (and return) an array?
Either way, can you elaborate on where this would come in handy? I’m not doubting it would, just curious how it would be used.
Cheers,
George
November 30th, 2005 at 8:14 am
XMLHttpRequest anyone?
November 30th, 2005 at 9:37 am
Got versions all of those in my own library, except the $ prototype jobbie… cheers for another interesting piece.
November 30th, 2005 at 10:07 am
Awesome list!
November 30th, 2005 at 10:50 am
@George: The dollar functions is a simple way to grab an element quickly. So instead of
document.getElementById('a');, you’d simply just do this instead:$('a');.And if you wanted a whole collection of elements, you can simply do this:
$('a','b',obj,obj2,'c','d');It really is a space saver and an elegant way to grab objects quickly.
@boohis: xmlHttpRequest is a real method straight from the DOM, not a custom function. Nevertheless I did search for a good ajax request function but wasn’t convinced of them being one of the best since as of this day and age we’re still evolving into ajax theory and development.
@pauly: As I figured. That’s exactly what I was shooting for.
@Neil: Thanks man. :)
November 30th, 2005 at 10:50 am
Hey Dustin!
Nice list! I’ve been reading so much about the prototype $() function that your post finally tipped me over into start using prototype, babysteps, with the $() function, :)
While putting together my own common.js file and I noticed your Cookie example has got some nasty \ (escape) errors in the function setCookie() class you would probably like to correct!
November 30th, 2005 at 10:53 am
@Kim: Drat the backslash! It’s caused from anytime I forget to escape “double quotes” inside code sections. Thanks for pointintg it out. Have fun with the dollar :)
November 30th, 2005 at 12:53 pm
Most of this looks like the Prototype library (http://prototype.conio.net/). I suggest just using that, it includes most of these.
November 30th, 2005 at 1:01 pm
@RH
I only see about three of these functions that would be found in the prototype library. Prototype has a version of addEvent() where you assign events through the Event.observe method. They also provide a document.getElementsByClassName, and lastly they have a Element.toggle for the show/hide trick.
With that said, I definitely recommend against running off and putting prototype on your system for the sake of a couple functions. Did you even look at the ten in the list?
November 30th, 2005 at 1:08 pm
Plus Prototype is a hefty chunk of code for just some simple functions. Isn’t it like 30KB?
November 30th, 2005 at 1:16 pm
Very nice. I will be adding this to MY common.js ASAP :)
November 30th, 2005 at 1:22 pm
What about a popup function and a browsersniff function?
Personally, I use those more than any of the ones here…
November 30th, 2005 at 1:35 pm
Good list. I use many of these in my day to day coding. I would like to make one addition/replacement: instead of inArray I use indexOf which will return the index of the element in an array instead of simply the proof of existence in the array.
November 30th, 2005 at 1:36 pm
I’ve got one minor complaint about your
inArray()function. It’s nothing big might I add, but you can improve performance by changing the for statement to this:for (i=(this.length-1); i>=0; i--)November 30th, 2005 at 1:47 pm
Couldn’t you write a $ function that would search for an element first by id then if none was found you could go on down the line of identifiers, name, tagname, class name, etc. It would be a little more bloated but would likely run just as fast since you could quit looking once you find the element.
November 30th, 2005 at 2:14 pm
For the insertAfter() function… I’m wondering if it will throw an error, if there is no “nextSibling”, if so, this function might work a bit better…
function insertAfter(parent, node, referenceNode){
if(referenceNode.nextSibling){
parent.insertBefore(node, referenceNode.nextSibling);
} else {
parent.appendChild(node);
}
}
November 30th, 2005 at 2:22 pm
One alternative (and possibly more efficient) way I’ve seen of getting elements by class is to take advantage of XPaths:
document.getElementsByClass = function(needle) {var result = document.evaluate(
"//*[@class='" + needle + "']", document, null,
XPathResult.ANY_TYPE, null);
var resultArray = new Array();
var element = "";
while (element = result.iterateNext())
resultArray.push(element);
return resultArray;
}
November 30th, 2005 at 2:36 pm
@Mike: Yea, it is like, 30k, and growing…
@Adam: Good for you. Glad to provide a small reference for ya :)
@TevK: I can understand your concern for the popup issue. However I was a bit deterred from the bad wrap popups have received and became reluctant to posting it as part of the top ten. Again, these are just my top ten that I’ve run into since developing for seven years.
But as for browser sniffing functions, shouldn’t we be beyond that by now with Object detection ;)
@Peter: indexOf is an actual JavaScript property. The inArray method allows you to get returned a boolean which often times can prove more useful when matching the ‘type’ of object. Notice the ‘===’ in the function. That’s a very important detail.
@Shawn Wilsher: how is that faster? It’s not like in php when you count() in the middle parameter which runs the function through each loop. The .length property is read only once in JavaScript. Nevermind that matter, I didn’t write this one to begin with, so I couldn’t claim it as ‘mine’.
@Jason: I wouldn’t change anything to the dollar function personally. However it sounds like you have a good idea going. The point of the dollar function is gather a collection of elements by ID, and that’s it. I really really like it that way :)
@Sammy: I don’t know. Haven’t tested that version quite yet.
November 30th, 2005 at 2:46 pm
here is my ajax setup:
Edited by author://
i use this to make calls out to php pages very handy
November 30th, 2005 at 2:47 pm
Are these scripts really “production” worthy? None of them seem to make allowances for the differences in browser DOM models, especially older browsers that do not recognize the getElemenetByX syntax.
Seems like this set of scripts needs to add a generic “getElement” function to handle the differences in browsers to be complete…
November 30th, 2005 at 2:53 pm
@Don: Please excuse the edit on your post. The code posted was a bit bloated and unreadable. Please feel free to link off to your examples that were posted. This was no way intended to remove your valuable functions, I just wanted to conserve some space on the comments before everyone starts posting long-winded functions of their own :) Please do stop by again.
@BlueLaser: Yes, they are production worthy. You can handle the BOM on your own end through separate functions.
Exactly. And that would be done on your own behalf.
November 30th, 2005 at 2:55 pm
Nice list. It inspired me to re-write and clean up my common js tools.
One thing I’ve started adding to many of my dom related functions is the ability to pass either an ID or the actual object and have the function figure it out. For example, with the toggle function:
Edited by Author://
November 30th, 2005 at 2:58 pm
Oy — code in comments isn’t a pretty thing. My kingdom for the PRE tag…
November 30th, 2005 at 3:00 pm
new link to my previous post http://www.alllinuxinfo.com/ajax.txt
November 30th, 2005 at 3:02 pm
@EyePulp: Please note your post was Edited. See Don’s original post
@Don: Thanks bro :) I appreciate it alot!
November 30th, 2005 at 3:04 pm
I must disagree with this post, sounded interesting but I’ve never used these functions apart from getElementsByClass, I hate relying on the users computer to do things for me. I mean there isn’t even a JS rollover script in there which I use more than anything with JS (and even that I don’t use too often). If you use all those functions regularly, you need to learn a new language!
November 30th, 2005 at 3:13 pm
A great list thank you!
November 30th, 2005 at 3:14 pm
@Toq: You don’t need JavaScript to do rollovers ;)
@Tim: Thanks Dude.
November 30th, 2005 at 3:23 pm
Awesome list, I probably use about half of those Thanks!
November 30th, 2005 at 3:32 pm
actually, the toggle(); function could be used as a simple rollover script.
November 30th, 2005 at 3:56 pm
Dustin, I didn’t realize the indexOf property was part of Firefox 1.5, so I guess it would go on a “Top 10 Javascript functions that should be implemented on all browsers but aren’t” list. :)
November 30th, 2005 at 4:37 pm
Dont forget about a debug() function, for printing debug messages to the page instead of having millions of alert boxes.
November 30th, 2005 at 4:39 pm
BlueLaser, at this point, most people are targeting Internet Explorer 6+/Windows, Firefox, Netscape 7+, Opera, and Safari 1.2+. All of these support getElementsByX; doing DHTML before these browsers was an exercise in pain.
November 30th, 2005 at 5:22 pm
hey this is a really cool javascript! i’ll be sure to use it on my next web designs. i really like the getelementbyclass function.
November 30th, 2005 at 5:33 pm
Good stuff here. Thanks
btw, your theme claims valid xhtml. Currently there are a few errors.
Keep up the good work.
November 30th, 2005 at 5:53 pm
thanks for providing these.. I mainly (ok exclusively), use javascript for form validation/popup windows/form fill-in.. However, I would really like to see already existing working examples of how to use top 10 javascript functions.. I think I am missing out on this and would really like to understand how these would be used via a demo (which is worth a 1000 words)..
November 30th, 2005 at 6:15 pm
Actually, it does get evaluated each time the loop is run. (Source)
The other alternative would be to to use
for inlike so:for( var i in this )I wasn’t slamming the code because it was bad either. I was just stating that there is a more efficient way of doing it. I still think this is a great list and I will be using some of it on sites that I’m working on.
November 30th, 2005 at 6:42 pm
@Shawn,
I went ahead and adjusted the link. That’s awkward that your link didn’t go through. It’s in the list of allowed html…
Anyway, thanks for the reference. Even knowing that, I still didn’t think it was accounted for in JavaScript since it was only a property and not, in fact, a method. Nonetheless it would be interesting to do a time test. I had originally done things the way you mentioned until I had heard other wise and didn’t bother. One other simple way you could do it is to just count the entire array ahead of time, assign it to a variable, then proceed with the for() loop.
But still, Thanks for your contributions! I always enjoy when visitors question optimization and offer alternative methods. It helps everyone.
November 30th, 2005 at 6:42 pm
I just wanted to add that I find it humorous when people don’t take the time to know what they are talking about before disagreeing with a post.
Why don’t you have a list of super cool DHTML menus, rollovers and mouse trails on your site Dustin?
November 30th, 2005 at 6:44 pm
[…] m JavaScript functions of all time Yet another “blog post as bookmark”: The top 10 custom JavaScript functions of all time. All the most handy functions on one page. Che […]
November 30th, 2005 at 6:48 pm
May I also note that you have been dugg.
http://digg.com/programming/Top_10_custom_JavaScript_functions_of_all_time
November 30th, 2005 at 9:44 pm
[…] p=438″ rel=”bookmark” title=”Permanent Link: “>
November 30th, 2005
javascript functions
This entry was posted
on Wednesd […]
November 30th, 2005 at 11:03 pm
[…]
davidbisset.com
Top 10 custom JavaScript Functions of All Time Not my title - it’s the link’s - but these are pretty darn useful for fellow JS coders out […]
December 1st, 2005 at 12:26 am
Holy cow, Dustin, I found this at the top of the del.icio.us popular page. Niiiiiice.
December 1st, 2005 at 12:42 am
@Aliotsy: Yea, “That’s pretty flippin’ sweet.” It also reached close to a 1,000 diggs and some how found its way onto Mozilla’s Developer Center Watch. Nonetheless, I stick to my words in the article :)
Anyway, hey man, it’s good to see you back around here ;)
December 1st, 2005 at 12:58 am
[…] dious aspect of Javascript-Programming, like for example the mising .getElementsByClas() Top 10 custom JavaScript functions of all time […]
December 1st, 2005 at 1:45 am
This is purely academic, but Shawn Wilsher’s suggestion to declare the array length in the for loop does make inArray() a little bit more efficient, as you can see for youself on my test page:
http://www.bitmess.com/sandbox/inarray.html
Method 1: EmbiMedia version
Method 2: EmbiMedia with Shawn’s mod
Just for fun I threw in…
Method 3: Convert to string and use indexOf()
Method 4: Use RegExp
Method 2 wins out by a thin margin over Method 1. If you don’t see a discernible difference in the timings, use a slower computer.
December 1st, 2005 at 4:05 am
Just a quick note — please don’t extend the
Arrayobject prototype in theinArrayfunction! Try this to see why:Array.prototype.foo = function(){ };
var testArray = [1, 2, 3];
for (var item in testArray) alert(item);
I’d recommend tweaking it to
function inArray(array, value)which is just as easy to use.Also, maybe replace
elements.push(element)in the$function withelements[elements.length] = elementas thepush()method isn’t supported by IE5.0 (only 5.5+).December 1st, 2005 at 5:29 am
@Angus: can you explain why? I’ve found what you’re saying to be absolutely true (whenever I add an inArray method to the Array it breaks other classes that rely on Array), but I’ve never understood why.
December 1st, 2005 at 6:02 am
Top 10 custom JavaScript functions of all time
It’s a bold title, but then again, these are ten+1 functions that anyone who has coded up some JS functions wants on their side.
December 1st, 2005 at 8:22 am
This is a great list but, the “$” function has to be the most inappropriately named function of all time. As a casual javascript developer, I would be sooooo confused by a function named dollar sign. What does that mean?
Name your functions by what they do, not by replicating what another language does. Please consider your fellow developer.
December 1st, 2005 at 8:27 am
Mmmkay… those functions are complete kludges; popularity does not define usefulness, it defines laziness.
I can rewrite every single one of those functions to be alot more useful than you’re suggesting; and I have.
Here’s a simple one that will give you multiple string | function event handlers:
addEvent = function(el,etype)
{
el[’on’+etype] = handler;
if(!el[etype]) el[etype] = [];
for(i = 2; i
December 1st, 2005 at 8:28 am
lol… and his comments don’t automatically handle < characters.
December 1st, 2005 at 8:37 am
@Tom: It adds the new method as a member of the array, so the above for loop would alert the foo method in addition to the 3 elements. It would also alert the length property. for/in loops are probably not the best way to loop through arrays - they are great for objects and collections. Hence I would not hold back in extending the Array object or any other core Javascript objects - it is a very useful ability.
Dustin, these functions are great, very fundamental. Suggestions made by others are not so fundamental, but rather functions that would make use of these.
A few functions for the DOM that I like to use are ones that get the first/next/previous/last node of a particular tag (inside a given parent node). Makes it easier to traverse the DOM if you don’t know all the id’s.
December 1st, 2005 at 11:47 am
Justin, one function that I really like (especially in relation to XML processing) is this one I wrote. I call it deepClone, and it clones a node from one document and attaches it to another one. I’m not a big fan of writing to innerHTML (since it’s not in a spec, I don’t want to depend on it being in a browser–I know, xmlhttprequest is the same way, I’m a hypocrite;) )
December 1st, 2005 at 12:27 pm
@Josh: That’s definitely a very useful function. To your dismay, you may also be happy that Firefox 1.5 is supporting innerHTML on xml :)…but then again, that’s only assuming the latest and greatest; you’re better off with your function :)
December 1st, 2005 at 1:25 pm
$ is the most irritating function name. This poor practice continues with $F, and, probably the worst part of it all, it has planted the seed that this type of naming convention is acceptable. Why not have a whole library of $, _, $A through $Z, $_$$_$_$$$_$_$ and names like this? Or, is the argument, “Well, just this one time because everyone knows what it means.”, justification enough?
Granted, $ is definitely shorter than document.getElementById, and it has enhanced functionality compared to document.getElementById, but getElements, or something intuitive, wasnt a good enough name?
Flame on…
December 1st, 2005 at 7:49 pm
Why didn’t document.write(”Hello World!”) make the list?
December 1st, 2005 at 8:00 pm
@Tom: Hmmm… I really contemplated that one… oh, i know why. Because it’s not a custom function.
December 2nd, 2005 at 4:41 am
Nice Work!!
I’ve done a little optimization & corrections to the code, you can find
the result here:
http://mykenta.blogspot.com/2005/12/10-funzioni-base-javascript.html
^_^;;
December 2nd, 2005 at 6:49 am
Top Ten custom JavaScript functions
Dustin Diaz collected the 10 mostly used custom JavaScript functions and yes, he is definitely hitting the bull’s eye: Out of ten functions I am using nine myself regularly.
Hey, develosphere is a nice one, saw it first there.
…
December 2nd, 2005 at 6:50 am
[…] y Top 10 custom JavaScript functions Dustin Diaz collected the 10 mostly used custom JavaScript functions and yes, he is definitely hitting the bull’s eye: […]
December 2nd, 2005 at 9:30 am
Top 10 custom JavaScript functions of all time
Dustin Díaz ha escrito semana ha venido con la lista de las 10 mejores funciones JavaScript de toda la historia.
La lista es completita, desde la gestion de eventos (addEvent, addLoadEvent), manejo del DOM (getElementsByClass, insertAfter) mezcland…
December 2nd, 2005 at 3:23 pm
Great list, we have many similar versions of these…
For our version of the toggle, we passed in the obj name and true/false for Show/No Show, and used getElementsByName to get the complete array of matching elements for the page, and sets all of them. Real time saver.
BO’C
December 2nd, 2005 at 6:03 pm
[…] vaScript Dustin Diaz released his personal recipe for a common JavaScript file. You know the file that includes the basic functions that any web site can u […]
December 3rd, 2005 at 10:29 pm
[…]Check out this great list of javascript functions.[…]
December 4th, 2005 at 6:07 am
[…] link) is associated with several tags. Search in weblog Daily* bonds (4 Dec ‘05) Top 10 custom JavaScript functionsI have to agree with this list of top JS function […]
December 5th, 2005 at 3:37 pm
[…] JavaScript functions! A must read! Pretty cool site design too (best viewed in Firefox)! read more | digg story
Leave a Re […]
December 6th, 2005 at 11:21 am
[…] MySQL security Part 2 | Cyberlot Technologies Group Latest Releases - DonationCoder.com Top 10 custom JavaScript functions of all time […]
December 6th, 2005 at 2:35 pm
Tom Clancy:
The reason that for (… in …) has shows you items that you add to Array.prototype is because for (… in …) goes through all properties on an object.
If you create a new method you are adding a new property, but the property is a Function. So it shows up in the list :/
Cheers,
Dion
http://ajaxian.com
December 7th, 2005 at 7:57 am
Great list!
A cleaner alternative to Array.prototype.inArray(str) is Array.prototype.has(str). It is shorter and more succinct.
I wrote this one several years ago and has been a great way to shorten lengthy string assertions for `if` blocks.
BTW - toggle() should have `function` before it to not confuse the non JS hackers.
JsD
December 7th, 2005 at 11:24 am
I have an updated to the toggle function.
It will preserve the display style if there is one already assigned to the element:
function toggle(s) {
var el = document.getElementById(s),els=el.style;
if (els.display!=’none’){
el._sty_disp_bk=els.display
els.display = ‘none’
} else {
els.display=el._sty_disp_bk||”"
}
}
December 8th, 2005 at 5:15 pm
Hmmm… I’m not really a Javascript expert, so pardon me for my stupidity. I can’t seem to get your getElementsByClass function to work. Firefox keeps telling me it’s undefined, but I saved it in my script.js file along with my other scripts (which work). Also, can one use it for getElementsByClass(’class’).style.display=(none) or something like that?
December 9th, 2005 at 12:42 am
[…] urrent computing environment.” “Top 10 custom JavaScript functions of all time…” http://www.dustindiaz.com/top-ten-javascript/ This entry was posted […]
December 10th, 2005 at 1:58 pm
A 3 line toggle function
function toggle (obj) {
state = (document.getElementById(obj).style.display==’none’)?’block’:'none’;
document.getElementById(obj).style.display = state;}
December 10th, 2005 at 2:04 pm
Gus,
The problem with your function is that it assumes your element is ‘block’ by default when in fact there is much more than ‘block’. Eg. inline, inline-block,table,table-row,table-cell, and quite a few others.
December 12th, 2005 at 8:12 am
[…] dominate, as would be expected. Nice download with all of them wrapped in a single file. http://www.dustindiaz.com/top-ten-javascript/ This entry […]
December 12th, 2005 at 4:39 pm
Dustin, thanks man. :)
My only question, why pass the parentNode to insertAfter?
function insertAfter(nPrevious,nInsert) {var nParent = nPrevious.parentNode;
if (nPrevious.nextSibling) {
nParent.insertBefore(nInsert, nPrevious.nextSibling)
} else {
nParent.appendChild(nInsert);
}
}
@ Shawn (comments 16, 39) rather than this:
for (i=(this.length-1); i>=0; i--)I believe you’re looking for this:
var i = this.length; while(i--)The while will auto terminate. Also check out Duff’s Device. There’s a js version somewhere out there I’m sure. :)
December 12th, 2005 at 8:36 pm
[…] at client supporting AOL, Yahoo, GoogleTalk, Jabber, MSN (tags: im ajax web chat web2.0) Top 10 custom JavaScript functions of all time (tags: javascript programming code development funct […]
December 13th, 2005 at 6:32 am
Great functions Dustin you have my complains.
Just one “notice” when using prototype functions (I used inArray, also created my “inMultiArray”). If you use them and for an example loop trought an array with “for (x in Array)” loop, the first x of an array will be prototype function names(depending how much prototypes you declared).
This “problem” can lead to unwanted results! In my case I use offen for (x in Array) loops and the only thing I could do is to change the prototype definition to a normal function. Have anybody on other idea?
PS There is a lot of JS code built and changeing it would be impossible.
December 13th, 2005 at 6:35 am
ahh plese delete this post and change my previous at the first line(ending) “complains”->”compliments”
Sorry man… ;-) translation problem….
December 13th, 2005 at 11:32 pm
[…] e wondering why I think this function is so sexy, I talked about it in an article about my top ten list of best JavaScript functions ever. No […]
December 14th, 2005 at 9:25 am
Good stuff Dustin. Thanks for consolidating and sharing. I have an addition if you so see fit.
Context: Extranet Application
Problem: Child windows remain open when a session times out and when a user navigates away from or closes the parent window.
Requirement: Close all child windows when a user navigates away and/or closes the parent window.
My solution is very similar to the EventCache class/object and actually uses this object and respective members. Let me know what you (and others) think. Refactor? Trash? Thanks again for you insight. See implementation below:
—-
Author removed code://Dan feel free to link offsite with an example of your code
December 15th, 2005 at 6:50 am
[…] tos, un reescalado de imgenes, una lista de funciones JavaScript imprescindibles, otra (de slayeroffice), y MochiKit.DOM, una API para […]
December 18th, 2005 at 2:59 am
[…] r: Startup Library
(tags: business startup entrepreneur howto articles technology)
[…]
December 18th, 2005 at 5:12 pm
well done. some goodies here including some that are new to me.
December 20th, 2005 at 6:30 pm
[…] JavaScript functions of all time Dustin Díaz ha venido esta semana con la lista de las 10 mejores funciones JavaScript de toda la historia. La lista es completita, desde la gestion […]
December 22nd, 2005 at 9:11 am
This stuff looks great! Is there a way I can reference stuff in common.js in another .js file, so I only have to inlude one
< script />tag in my html?December 22nd, 2005 at 10:53 am
@Mark: Yep. That’s correct. You now hold the secret to easier web development :)
December 22nd, 2005 at 12:19 pm
Umm, I don’t think you understood my comment. I’d like to be able to reference (i.e., inherit classes, use functions, etc.) from one .js file in another without having to make sure all the JavaScript files are included as seperate script tags in the HTML file that uses them. Basically, I’d like to be able to have the same sort of functionality that
#include "File.h"does in C.Is there a way to do that?
December 22nd, 2005 at 2:06 pm
Hope that helps.
December 22nd, 2005 at 5:02 pm
[…] nd addEvent */ // addEvent() found @ http://www.dustindiaz.com/rock-solid-add-event/ // $() found @ http://www.dustindiaz.com/top-ten-javascript var togBar = { bar : null, nest : null, init : function() { this.bar = $(’sideBar’); this.nest = […]
December 22nd, 2005 at 5:03 pm
[…] nd addEvent */ // addEvent() found @ http://www.dustindiaz.com/rock-solid-add-event/ // $() found @ http://www.dustindiaz.com/top-ten-javascript var togBar = { bar : null, nest : null, init : function() { this.bar = $(’sideBar’); this.nest = […]
December 22nd, 2005 at 5:03 pm
[…] nd addEvent */ // addEvent() found @ http://www.dustindiaz.com/rock-solid-add-event/ // $() found @ http://www.dustindiaz.com/top-ten-javascript var togBar = { bar : null, nest : null, init : function() { this.bar = $(’sideBar’); this.nest = […]
December 22nd, 2005 at 5:04 pm
[…] nd addEvent */ // addEvent() found @ http://www.dustindiaz.com/rock-solid-add-event/ // $() found @ http://www.dustindiaz.com/top-ten-javascript var togBar = { bar : null, nest : null, init : function() { this.bar = $(’sideBar’); this.nest = […]
December 23rd, 2005 at 7:42 am
The DOM and the ECMA-262 (or JavaScript) specs are totally, completely separate. Cookies, for instance, have nothing to do with the DOM. Neither does the Array built-in object. Neither do many other sentences on this page containing the word DOM! For example, the section about
inArray:That’s incorrect. It is a function. The function is called
inArrayand is a property of theprototypeproperty of theArraywhich is defined in ECMA-262 and has, again, nothing to do with the DOM. Please, read the relevant specs. Much of this article is just downright wrong.December 23rd, 2005 at 11:46 am
Xaprb,
The cookie functions are in fact functions that aid in setting cookies “with JavaScript”
And the inArray property, sorry to have confused you again.
Would you like to share any more of your professional advice and tell me what else I should read? Perhaps my diet is wrong? Should I be eating healthier too?
December 23rd, 2005 at 2:10 pm
[…] nd addEvent */ // addEvent() found @ http://www.dustindiaz.com/rock-solid-add-event/ // $() found @ http://www.dustindiaz.com/top-ten-javascript var togBar = { bar : null, nest : null, init : function() { this.bar = $(’sideBar’); this.nest = d […]
December 24th, 2005 at 12:00 pm
Dustin, my apologies for sounding like an @$$. I’m saying that JavaScript and the DOM are not the same thing. That’s all. JavaScript can interact with the DOM. But it exists completely apart from it — even completely apart from a browser. It is a scripting language that the browser hosts. The browser exposes certain objects (the document, the window etc) to JavaScript, but that by no means makes the built-in Array object part of the DOM.
December 24th, 2005 at 4:56 pm
Right. You got that correct. Often times I use them so interchangabley, I forget I’m mixing them up.
JavaScript is in fact a language that manipulates the DOM - and so many people get that wrong.
December 29th, 2005 at 8:16 am
[…] « Verwaltung von Digitalfotos Moderne Javascript Top 10 Top 10 custom JavaScript functions of all time This entry was posted […]
December 30th, 2005 at 7:43 am
Dustin,
just curious… you’d want your getElementsByClass () to be as fast as possible. Would it not be more efficient to use the For … In … instructions instead of getting the length and then looping using the index? I know languages where iterating a collection in such way can kill the efficiency of the program.
Jean-Marc
January 1st, 2006 at 4:08 am
[…] Un petit classement des 10 meilleures fonctions Javascript du moment, ça serait idiot de passer côté de celles-ci qui […]
January 2nd, 2006 at 3:38 pm
[…] Array prototype methods, but Dustin Diaz has listed my inArray JavaScript method among his Top 10 most useful functions of all time. Thanks for the mention! This method as originally liste […]
January 3rd, 2006 at 6:37 am
I’ve been using an extended version of the $ function for a while - finally wrote it up on my blog, might be of use to somebody:
A better $ function
January 4th, 2006 at 5:35 pm
11. Add rollovers:
function addRollover(obj, url) {
(new Image).src = url
obj.onmouseover = function () {
var lastSrc = this.src
this.src = url
this.onmouseout = function() { this.src = lastSrc }
}
}
allImgs = document.getElementsByTagName(’img’)
for(i=allImgs.length-1; i>=0; i–) {
value = allImgs[i].attributes.rollover ? allImgs[i].attributes.rollover.value : allImgs[i].rollover || 0
if (value) addRollover(allImgs[i], value)
}
January 6th, 2006 at 12:19 pm
[…]
links for 2006-01-06
Filed under: Bookmarks | Lindsay @ 12:20 pm
Top 10 custom JavaScript functions of all time Well, maybe not the best of all time, but definitely […]
February 10th, 2006 at 12:26 am
[…] In November of last year I published an article discussing what I thought the top ten custom JavaScript functions were, and to th […]
February 10th, 2006 at 11:01 pm
[…] yle.display = (el.style.display != ‘none’ ? ‘none’ : ” ); } Cool. Hey, ever heard of the dollar function? If that’s sittin’ around somewhere, let’s use it! toggling with […]
February 25th, 2006 at 6:15 pm
[…] Dustin Diaz released his personal recipe for a common JavaScript file. You know the file that includes the basic functions that any web site can use. We’ve all grabbed some of these scripts from here and there and its nice to see it one-stop shopping packaging. […]
March 25th, 2006 at 11:51 am
domEl() - custom function for easier DOM manipulation…
After reading the “TOP 10″ custom functions list by Dustin Diaz I decided to publish this custom function. Today I can’t imagine DOM scripting without it, and with Dustin’s top-list members $() and getElementsByClass() it gives …
March 29th, 2006 at 10:31 am
[…] Dustin Diaz did not answer this one but fortunately I remembered he did an article top-ten-javascript. I got his top 5 from there: The Prototype $ Dollar Function, getCookie(), setCookie(), deleteCookie(), inArray() and insertAfter(). […]
April 5th, 2006 at 3:04 pm
[…] As I wasn’t feeling like writing a function for traversing the whole DOM tree for searching elements class names, I also used a function, getElementsByClass by Dustin Diaz, to discover the elements with a certain class name. So yes, the rest was pretty easy […]
April 6th, 2006 at 12:03 am
[…] Sé que es un recurso que ya tiene su tiempo, pero yo lo he descubierto ahora y estoy encantado: Top 10 custom JavaScript functions of all time . […]
April 11th, 2006 at 6:19 am
[…] Dans la lignée du Top 10 custom JavaScript functions of all time de Dustin Diaz, voici quelques fonctions DOM qui me servent de temps en temps. […]
April 20th, 2006 at 2:27 pm
[…] A very nice top 10 of the most used (custom or native) JavaScript functions! A must read!read more | digg story No Comments so far Leave a comment RSS feed for comments on this post. TrackBack URI Leave a comment Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> […]
May 10th, 2006 at 12:14 am
[…] Now with better audio equipment, in this episode I paid a revisit to my Top Ten JavaScript Functions of all time entry from November of 2005 and did a complete analysis explaining the pros and cons of each function and what could be improved, and if, perhaps, there are better functions today as an alternative. Regardless, the functions were good for their time, but with JavaScript at the forefront of development, new ones are being reborn every day and are simply replacing the old. […]
May 18th, 2006 at 2:11 pm
[…] Il cookie-pensiero Ricevere e modificare il dato presente all’interno di un cookie non è operazione difficile, come dimostrano le funzioni che si trovano sul podio di questa classifica di Dustin Diaz. Ma se i dati da inserire nello stesso cookie sono più di uno, tipo - uhm, non so - un ‘font-size’ ed un ‘font-family’? Spulciando nella sezione Opzioni/Privacy/Cookie/MostraCookie del mio browser alla ricerca di inspirazione, una buona soluzione è arrivata dal Docking Boxes di Brother Cake (che permette il drag’n’drop dei box nell’amministrazione del vostro Wordpress 2), in cui due dati diversi vengono inseriti nello stesso cookie intervallati con un ‘&’ e ogni nome del dato è separato dal proprio valore tramite un ‘=’. Sviando le 1585 righe del codice (Allora, eprefix-running…“Marcoo…” Uhm, null-undefined. “Marcoooo….” Eh?Oibò, chi è? “Sono il tuo letto…” Aspetta, fammi finire di legger il savedata prima delle 3 meno dieci. “Ma non hai sonnoo…” Va bene, dai, alle 2 arrivo. “Oggi ho le lenzuola più morbide…” Per favore, ho uno script da rifinire! Uff, però, ora che mi ci fai pensYaaawn…5 minuti eh…perch…ronf.) ho ipotizzato una soluzione simile che restituisse un document.cookie (la stringa che contiene i valori di tutti i cookie legati ad un particolare dominio) di questo genere: […]
May 19th, 2006 at 7:37 pm
[…] The cookie time. Get and modify the data inserted in a cookie isn’t a difficult operation, as prove the functions on the podius of this Dustin Diaz’s chart. But if the data to insert in a cookie are more than one, like uhm - i don’t know, a ‘font-size’ and a ‘font-family’? Taking a look at the ‘Options/Privacy/Cookie/ViewCookie’ section of by browser in search of the inspiration, a good solution arrived from the Docking Boxes by Brother Cake (the same that allows the box’s drag’n’drop’n’open’n’close in your Wordpress 2.0 admin), where two different data are stored in the same cookie splitted by by an ‘&’ and every data name is separed from his value by an ‘=’. I haven’t the time to search and undestand the corrensponding functions in this 1585 lines (commented version) code, so I supposed a similar solution that returns a document.cookie (containing the values of all the cookie related to particular domain) like this: […]
June 9th, 2006 at 12:07 pm
[…] 10 custom Javascript functions of all time 6/9/2006 12:58 | Permanent Link| […]
June 13th, 2006 at 8:52 pm
[…] read more | digg story Explore posts in the same categories: coldcase […]
June 29th, 2006 at 2:18 pm
[…] Yes, I discovered a few of them prior to spotting the article Top 10 custom JavaScript functions of all time […]
July 5th, 2006 at 11:03 pm
Top10 selbstgebauter Javascript Funktionen…
Hier eine Liste von selbstgebauten Javascript Funktionen.
Mit Erläuterungen und sehr vielen nützlichen Kommentaren.
http://www.dustindiaz.com/top-ten-javascript/
……
July 24th, 2006 at 10:50 pm
[…] “If there was ever a universal common.js shared among the entire develosphere, you’d fine these ten (plus one bonus) functions. It would be the swiss army knife no developer would go into production without.” […]
August 7th, 2006 at 3:58 am
[…] The script is built from the prototype $ and getElementsByClass functions as presented by Dustin Diaz. Filed under: Tech Attachment(s): tabbable.0.1.zip […]
October 12th, 2006 at 12:11 pm
[…] That’s quite a statement, it’s probably worth a look http://www.dustindiaz.com/top-ten-javascript Related Posts: 9 JavaScript Tips You May Not Know / Finding fresh inspiration / JonDesign’s Smooth SlideShow Library / Dealing with the Digg Effect - A First Hand Story and Advice on Keeping Your Site Up / […]
October 20th, 2006 at 9:26 am
[…] Dustin Diaz’ article “top 10 javascript scripts”: http://www.dustindiaz.com/top-ten-javascript […]
November 8th, 2006 at 11:48 am
[…] Me inspirei (copy,paste) por aqui. […]
November 15th, 2006 at 9:14 pm
[…] And before you know it, they’re adding an event to every element in sight, and their formally pristine HTML looks like cat sick on a paisley carpet. If you’ve reached this point, then you want to look in to the addEvent() function that you’ll find here. Every function on that list will be of some use to an even half-serious JavaScript programmer, but for now I’ll just talk about adding events. Aside from helping you clean up your code, the addEvent() function offers you a painless way to add the same event to a large number of elements - a long list of <li>s for example. It’s common to call addEvent() when your page loads (see the second function in the list), but you can also use it when any other function is called, to change the behaviour of a rolled-over or clicked element - maybe the second time the button above is clicked you want it to fade in a picture of Scott Baio, just to teach the user a lesson. […]
November 24th, 2006 at 5:40 pm
[…] Dustin Diaz, ha hecho una recopilación de las mejores funciones en Javascript, cuando empezé a leer este artículo pensé, “Serán las 10 que más le han gustado a él…”, he terminado de leerlo y aplaudo su elección, sin duda son las mejores, o por lo menos las más útiles. […]
February 7th, 2007 at 12:45 pm
[…] Top 10 custom JavaScript functions of all time (tags: javascript functions list) Posted in Daily Links by phil.leitch RSS 2.0 […]
March 8th, 2007 at 11:18 pm
[…] Top 10 custom JavaScript functions of all time (tags: javascript) […]
March 12th, 2007 at 4:09 am
[…] Mentre in rete impazzano discussioni su quali siano veramente le 10 funzioni JavaScript più utili per semplificare e migliorare lo sviluppo di siti Web 2.0, Matt Dibb, uno sviluppatore Londinese di IBM, pubblica nel suo blog una classifica in contro tendenza, dove più che mostrare codice, parla delle dieci domande più frequenti di forum e comunità di giovani webmaster, o per meglio dire, delle dieci cose che JavaScript non può fare. […]
March 17th, 2007 at 3:23 am
[…] Top 10 custom JavaScript functions of all time I’ve been reviewing JavaScript for awhile now. I’d love to build a WordPress theme that really took advantage of it but my JavaScript and Ajax skills are lacking. This particular page shows off a few JavaScript functions that I think could be really hel (tags: JavaScript) […]
March 19th, 2007 at 9:23 am
[…] Top 10 JavaScript functions of all time http://www.dustindiaz.com/top-ten-javascript/ […]
March 20th, 2007 at 4:23 pm
[…] Recent Bookmarks - del.icio.us/silus Top 10 custom JavaScript functions of all time 03/20/2007 08:16 PM Guantanamo Cell Replica - Quicktime VR 03/20/2007 06:48 PM 8 web menus you just can’t miss 03/20/2007 04:57 PM free university lectures - computer science, mathematics, physics 03/20/2007 04:28 PM umi2.gif (GIF Image, 712×715 pixels) 03/20/2007 04:00 PM Recent Myspace Zara : hey, have you heard if we are doing anything Sunday re. mothers day?? I fancy going out, but best not if we have any family thing planned… anyway hope your good bro x 03/13/2007 08:15 AM Extricated : still no sign of the rock… do you have a pic of the one over there? 02/19/2007 10:37 AM BOMB FACTORY : IMAGE 02/18/2007 10:08 AM […]
March 22nd, 2007 at 4:10 pm
[…] Top 10 custom JavaScript functions of all time http://www.nuzzaci.com/iffound/2007/02/08/15:13:31 - 1k - Similar pages […]
April 2nd, 2007 at 7:05 pm
[…] Dustin Diaz has some really easy functions for managing cookies in his post Top 10 custom JavaScript functions of all time. […]
May 2nd, 2007 at 10:37 am
[…] There are many dollar sign functions out there, especially in the Javascript packages such as Prototype or MooFX. Peter-Paul Koch over at Quirksmode offers a cross-browser version of document.getElementById. Let’s combine all the goodness from each of these to make a souped-up $() dollar sign function that works in most browsers, and is not dependant on the DOM implementation of just one. It’s actually 2 functions, the $() and then a helper function. […]
May 2nd, 2007 at 2:05 pm
[…] I don’t know how I landed in Dastin Diaz’s page about Top 10 custom JavaScript functions of all time , but I found the list painfully true. It’s not that I did not know about these functions, but it’s still enlightening to re-read the list once in a while. […]
September 21st, 2007 at 10:39 pm
[…] Top 10 custom JavaScript functions of all time […]
November 21st, 2007 at 10:15 pm
[…] A very nice top 10 of the most used (custom or native) JavaScript functions! A must read!read more | digg story Sleep Deprivation Doubles Risks of Obesity […]
November 27th, 2007 at 10:50 am
[…] A very nice top 10 of the most used (custom or native) JavaScript functions! A must read!read more | digg story Similar posts: Socket Programming in Ruby […]
December 5th, 2007 at 10:44 am
[…] Правильная статья от Дастина Диаза (Dustin Diaz) с примерами десяти функций на JavaScript. […]
December 6th, 2007 at 11:57 am
[…] article - Top 10 custom JavaScript functions of all time - talks about common javascript functions (perhaps put into a common.js file). It’s a little […]