JS: 10 (or so) Functions I Can’t Live Without
Below are ten JavaScript functions that, over the course of several years, I have found to be indispensable, awesome, and at times life-saving.
1. addEvent()
This function takes all the work out of determining the correct way to add an event to an element (depending on the user’s browser).
function addEvent(obj, eventtpye, functn, usecapture) {
if (obj.addEventListener) {
obj.addEventListener(eventtype, functn, usecapture);
return true;
} else if (obj.attachEvent) {
return obj.attachEvent('on' + eventtype, functn);
} else {
obj['on' + eventtype] = functn;
}
}
2. addLoadEvent()
This function adds events that trigger after the page has loaded by attaching them to the onload event handler. It first stores the existing onload contents to a variable. Then, if the onload handler is not set to a function, it assigned the given function to the handler. Otherwise, it adds the function to the existing onload contents.
function addLoadEvent(functn) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = functn;
} else {
window.onload = function() {
oldonload();
functn();
}
}
}
Note: Another way of adding events to the onload handler is to simply use the addEvent() function, as described above, like so:
addEvent(window, 'load', functn1, false); addEvent(window, 'load', functn2, false); // etc.
3. getElementsByClass()
You would think that JavaScript would already have such a function, but surprisingly (or not, depending on your cynicism) it isn’t an original DOM method. We have getElementById(), getElementsByName(), and getElementByTagName()… so why not a getElementsByClass() method? Well, here it is:
function getElementsByClass(findclass, node, tag) {
var classElems = new Array();
if (node == null)
node = document;
if (tag == null)
tag = '*';
var elems = node.getElementsByTagName(tag);
var pattern = new RegExp('(^|\\\\s)'+finclass+'(\\\\s|$)');
var j = 0;
for (i = 0; i < elems.length; i++) {
if (pattern.test(elems[i].className)) {
classElems[j] = elems[i];
j++;
}
}
return classElems;
}
To return an array of all anchor (<a>) elements of the “foo” class, call the following:
var foos = getElementsByClassName('foo', document, 'a');
4. toggle()
The strict definition of “toggling” is hiding or showing an element upon the occurence of an event. This function, which does just that, is short, simple, and to the point.
function toggle(objid) {
var elem = document.getElementById(objid);
elem.style['display'] = (elem.style['display'] == 'none') ? '' : 'none';
}
5. insertAfter()
One would think that this would be a DOM core method (like getElementsByClassName()) but, sadly, it is not. Fortunately, it only requires one line of code, though it is hard to remember and is thus suited to having its own function.
function insertAfter(parent, node, refNode) {
if (refNode.nextSibling)
parent.insertBefore(node, refNode.nextSibling);
else
parent.appendChild(node);
}
6. inArray()
This is yet another simple method that really should already be built into the JavaScript DOM. While not a function, it is a prototype that extends the existing Array object to add this functionality.
Array.prototype.inArray = function(value) {
for (i = 0; i < this.length; i++) {
if (this[i] === value) return true;
}
return false;
}
7. getCookie(), setCookie(), delCookie()
I included all three of these methods into one entry because they all go together like gears in a machine. PHP’s implementation of cookies is such an easy, painless process, but this is not so for JavaScript. These three will be like Vicodin after the pain of dealing with cookies in JS.
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.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() : '') +
(path ? ';path=' + path : '') +
(domain ? ';domain=' + domain : '') +
(secure ? ';secure' : '' );
}
function delCookie(name, path, domain) {
if (getCookie(name))
document.cookie = name + '=' +
(path ? ';path=' + path : '') +
(domain ? ';domain=' + domain : '') +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
8. $()
The Prototype Dollar Function
In all honesty, this function was new to me as of recently. It never really occurred to me to have a function whose name consists of one character (a dollar sign, no less!), that takes in either strings or objects and any number of arguments, and that returns either one object or an array of objects.
Now I can’t live without it. Here it is:
function $() {
var elems = new Array();
for (var i = 0; i < arguments.length; i++) {
// For each argument passed to $()
var elem = arguments[i];
if (typeof elem == 'string')
elem = document.getElementById(elem);
if (arguments.length == 1)
return elem;
elems.push(elem);
}
return elems;
}
It’s only a few lines of code, too! You can use it to call up one object in one way:
var textbox = $('mytextbox');
or many objects in many ways:
var images = $(objImage1, 'myimg', 'badimage', objImagePlaceHolder);
The return value is always an object, or an array of objects.
9. getXMLHttpObject()
If you’re working with AJAX and have to keep checking your notes for the function that returns the XML-HTTP object, this one’s for you. This works for nearly all browsers in existence.
function getXMLHttpObject() {
var xmlHttp;
// IE only...
try {
xmlHttp = new ActiveXObject("Msxml2.xmlHttp");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.xmlHttp");
} catch (E) {
xmlHttp = false;
}
}
// All other browsers...
if (!xmlHttp && typeof xmlHttpRequest != 'undefined') {
try {
xmlHttp = new xmlHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
return xmlHttp;
}
10. randomRange()
Last, but certainly not least, is the ultra-useful randomRange() function, which returns a random integer between two numbers, inclusive.
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Conclusion
I keep every single one of these functions inside one external JavaScript file called common.js and call it in the header file that I include in all pages of whatever site I’m working on. That way, all the code is available to me no matter what, whenever I need it. And trust me, I’ve needed it plenty of times in the past, and will continue to need them well into the future.
No comments yet.