Write a comment on this article
Here is a collection of useful JavaScript functions for your JavaScript library.
Quickmenu: The dollar ($) function, getElementsByClass(), toggle(), inArray(), has(), indexOf(), find(), XMLHttpRequest, Cookie handling, trim(), Numeric sort, Select node, Disable enter key
The following function is a shortcut to a better document.getElementById. You can pass element id's and/or references and will get either a reference (if you passed only one parameter) or an array of references (if you passed more than one parameter). It's possible to use the dollar sign ($) as a function name because it's reserved in JavaScript. Another option would be the underscore (_).
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;
}
Here is an example how you can use the dollar function:
var elem1 = document.getElementById("layer1");
var elem2 = document.getElementById("layer2");
var elems = $(elem1,elem2,"layer3","layer4");
/* alert the classes of the selected elements */
for(var i=0;i<elems.length;i++){
var elem = elems[i];
if(elem){
alert(elem.className);
}
}
Try this example here: The_dollar_function.html.
Attention! If you are using any JavaScript libraries like MooTools or jQuery, be aware that these libraries might already have implemented the dollar function which would overwrite your function depending on the order you import your JavaScript files.
Another function from Top 10 custom JavaScript functions of all time. It implements the missing DOM function getElementsByClass() and it does what it says. You can try this function here: getElementsByClass.html.
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;
}
A simple but useful function to toggle the display of an element which means visible elements become invisible and vice versa. You can either pass an element id or a reference. You can try this function here: toggle.html.
function toggle(elem){
if(elem){
if(typeof(elem)=="string"){
elem = document.getElementById(elem);
}
if(typeof(elem.style)!="undefined"){
if(elem.style.display!="none"){
elem.style.display = "none";
}else{
elem.style.display = "";
}
}
}
}
An often needed method for arrays is to check if an array contains a specific value. There are several possibilities and options to implement an according function. You can either return a boolean if the value was found (inArray(), has()) or the index of the value inside the array (indexOf(), find()). Here is a possible version from Top 10 custom JavaScript functions of all time. It adds the method inArray() to the JavaScript prototype Array, so if you are using for(var key in myArray) you will also get "inArray" (just to keep in mind). You can try this prototype function here: inArray.html.
Array.prototype.inArray = function(value){
var i;
for(i=0;i<this.length;i++){
if(this[i]===value){
return true;
}
}
return false;
};
The other option would be to return the index of the value in an array. The following function from Ten Javascript Tools Everyone Should Have returns an array containing the indexes of the found elements or "false" if no match was found. This is also a prototype function, so keep in mind that it will also be returned when using for(var key in myArray).
Array.prototype.find = function(searchStr){
var returnArray = false;
for(var i=0;i<this.length;i++){
if(typeof(searchStr)=="function"){
if(searchStr.test(this[i])){
if(!returnArray){
returnArray = [];
}
returnArray.push(i);
}
}else{
if(this[i]===searchStr){
if(!returnArray){
returnArray = [];
}
returnArray.push(i);
}
}
}
return returnArray;
};
AJAX (Asynchronous JavaScript and XML) allows you to send a request to your server without reloading the whole page. This way you can update fragments of your page easily and very fast. The following function creates a new XMLHttpRequest object, sends the given data and calls the passed function (response handler). A short demo is available here: XMLHttpRequest.html.
/* parameters:
*
* method = "get", "post" or "head"
* url = URL (must be on same domain)
* data = data to send (if post)
* respond = response handler (a function)
* asynchronous = "true" or "false"
(if "false" browser will wait until request is finished)
*/
var request = null;
function openRequest(method,url,data,respond,asynchronous){
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){}
}
}
if(request){
request.onreadystatechange = respond;
request.open(method,url,asynchronous);
request.setRequestHeader("content-type","application/x-www-form-urlencoded; charset=UTF-8");
request.send(data);
}else{
alert("Your browser does not support XMLHttpRequest!");
}
}
JavaScript allows to set and delete cookies, provided the browser allows it. Anyway, the way to set, read and delete a cookie is very poor. The following three functions from Top 10 custom JavaScript functions of all time facilitate the work with cookies. Here is an example: Cookie_handling.html.
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(): "")+
((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";
}
}
trim() is a function to remove blanks at the beginning and end of a string. Unfortunately, JavaScript's prototype "String" does not have such a function built in. Thanks to prototyping you can add this function easily. Two other useful functions would be to remove blank only at the beginning (ltrim) or at the end (rtrim). Keep in mind that these prototype functions will also be returned when using for(var key in myArray).
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function(){
return this.replace(/^\s+/g,"");
}
String.prototype.rtrim = function(){
return this.replace(/\s+$/g,"");
}
/* useage */
" text ".trim(); // returns "text"
" text ".rtrim(); // returns " text"
" text ".ltrim(); // returns "text "
The JavaScript prototype "Array" has a built in function sort() which sorts its values ascending. Anyway, numbers will not be sorted correctly (55 comes before 6). However, it is possible to pass a function which specifies the sort order, and this helps to sort numbers correctly too. This short prototype function is from Ten Javascript Tools Everyone Should Have. Again, keep in mind that this prototype function will also be returned when using for(var key in myArray).
Array.prototype.sortNum = function(){
return this.sort(function (a,b){ return a-b; });
}
/* useage */
var myArray = new Array(123,56,8,99,77,23);
myArray.sort(); // returns 123, 23, 56, 77, 8, 99
myArray.sortNum(); // returns 8, 23, 56, 77, 99, 123
A handy little function is selectNode(). It selects the content of a node as if the user would select it with his mouse cursor. This is very useful if you provide some source code on your page and want to give the user the possibility to select your code with one click rather than selecting it slowly with the mouse cursor. The function is from Martin Honnen. You can try a short example here: Select_node.html
function selectNode(node){
var selection, range, doc, win;
if((doc=node.ownerDocument) && (win=doc.defaultView) &&
typeof win.getSelection != "undefined" &&
typeof doc.createRange != "undefined" &&
(selection = window.getSelection()) &&
typeof selection.removeAllRanges != "undefined"){
range = doc.createRange();
range.selectNode(node);
selection.removeAllRanges();
selection.addRange(range);
}else if(document.body &&
typeof document.body.createTextRange != "undefined" &&
(range = document.body.createTextRange())){
range.moveToElementText(node);
range.select();
}
}
When a user is filling in a form and he presses the enter key while he is inside a textfield, the form will be submitted. This might happen accidentally or because the user is used to jump to the next input field by pressing the enter key. To avoid incomplete inputs, you can disable the enter key in textfields with the following script from WebCheatSheet.com. You can try an example here: Disable_enter_key.html.
function stopRKey(evt){
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if((evt.keyCode==13) && (node.type=="text")){
return false;
}
}
document.onkeypress = stopRKey;
JavaScript, function, dollar, underline, class, array, AJAX, cookie, string, sort, node, select, form
If you have a question or a problem and you're looking for a solution, please use the forum. Comments might not be answered.