The 10 most commonly used JavaScript custom functions

Source: Internet
Author: User
Tags date array comments functions reference setcookie window domain
javascript| function

If there was ever a universal common.js shared among the entire develosphere, your ' d fine these ten (plus one Bonu s) functions. It would is the Swiss Army Knife no developer would go into production. They have no doubt been tested tried and true and have proven usefulness and helpfulness to all those the who ' ve used them. So without further ado, this is are what I believe to the top ten greatest custom JavaScript functions in.

Upon Further reading this article, it's suggested that's for this article in particular the reader should use a alternate Style with cleaner whitespace and larger margins. This are available by selecting clean with whitespace available on the side bar.

) Addevent ()

Surely a staple to event attachment! Regardless to what version for use written by whatever developer, it does what it says. Course as your might of known, I ' ve put together quite a handy version myself recently of Addevent () with some From the contest winner and Mark Wubben along with a few minor syntax. But just to being fair to Scott Andrew, this is the original this 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 through many others as a simple way to add events to trigger after the Page has loaded. This is course attaches all your events to the OnLoad event handler which some still as necessary, nevertheless it doe s exactly what it ' s supposed to, and does it.

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 are to simply assign multiple event listeners to the window by using addevent () as Descri Bed in number 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. As you might expect, I humble self has even had a crack at it. This function is spawned from developers needing a quick and elegant way of grabbing elements by a className and to a dev Eloper ' s surprise, it's not a original DOM method as one might think...afterall, we have getElementById ,, getElementsByName() , getElementsByTagName what the hell Happened to getElementsByClass ??? Here it 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 are 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 are more like a mini-library and not quite so light on the weight factor, but still, a very k Ick-ass function. Due to its length (and CC lisencing) I won ' t post it in this site. Full documentation can is found on the Mycssquery reference and download page.

6) Toggle ()

To is totally honest, there are probably more variations the this function than there needs to be. The history of ' toggling ' basically comes down to showing/hiding a element upon an event being fired. To make matters much simpler, I too have put one together. But by no means it considered the ultimate toggle function, But It does do basic functionality of showing and Hidin G.

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 and this is even though one would have thought this too would is a DOM C Ore method. But just like getelementsbyclass, it isn ' t. So rather than pulling the function is straight out of the book, I'll leave that up to your buy it yourself. Instead I ' ve pulled this simple to public domain:

InsertAfter () on public domain

function insertAfter(parent, node, referenceNode) {parent.insertBefore(node, referenceNode.nextSibling);}

4) InArray ()

This too was very sad 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 does this in PHP, it's gotta be in JavaScript." So, this is extension makes it work just like you ' d expect if you ' re a PHP developer. Here's 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 easy, and it's easy for one main reason, they work just like the functions below. All three of this functions were found to is 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 ((!st ART) && (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));d Ocument.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)? ";p ath=" + 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 is straight up kicks so much ass. "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<elements.length;i++ ) {    alert(elements[i].id);  }}

Tell me that ' s not beautiful! Short is by name and but by reference. It takes in strings, it takes objects too. Can pass it one argument, or pass it many! This by far are my favorite function to all time which'll provide years and years of handiness.

And so would they all ...

I hope this quick and handy list of JavaScript functions has been as useful for your as they have for me. And for your downloading pleasure, this is the all this functions wrapped up in a common.js to you.

After the fact

Added after the comments or so ...: Ok, I can understand everyone ' s point of view as it comes to ' ten being the best‘. The fact of the matter is, this is what I am the best. If Dean Edwards wrote he top ten, I ' m sure it would to be different. If Stuart Langridge wrote his list, it too would is different. I mainly concentrated my list on the DOM. Browser detection are up to the developer at hand. Ajax functions I felt do not qualify as a ' all timer ' mainly because Ajax are still in it infancy and has yet to impress Me with something amazingly useful. For those wishing to just push this functions aside and slap on prototype to their documents, go ahead and slap on the ex Tra 30k If you feel that ' s necessary. Nevertheless, thank you thus far for the wonderful comments. I still hope this small list would come in handy for quite the time. And believe me, there are hundreds of other great functions this could make it here. Just because it isn ' t here, the doesn ' t mean it ' s not good. Just Use your imagination



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.