FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home » Javascript » Top Javascript Code Snippets for 2007

Top Javascript Code Snippets for 2007

Top Javascript Code Snippets for 2007 » Top Javascript Code Snippets for 2007

Top Javascript Code Snippets for 2007

November 12th, 2007

Javascript examples for web developers in 2007. All of my favorite unobtrusive javascript code and javascript examples that I use while building best-practices web sites. If you are even a remotely talented webdesigner who utilizes javascript, you will love this article!

NOTE: I am kinda obsessed with robust and highly accessible and unobtrusive code, as well as web-standards and cross-browser functionality, so this code is all good baby.


The javascript examples

Get the object!

//------------------------------------
// gi
function gi(eleName){
    if(document.getElementById&&document.getElementById(eleName)) return document.getElementById(eleName)
    else if(document.all&&document.all(eleName)) return document.all(eleName)
    else if(document.layers&&document.layers[eleName]) return document.layers[eleName]
    else return false
}

This handy function loads any function on page load, can be used multiple times!

//------------------------------------
// addLoadListener
function addLoadListener(fn){
    if(typeof window.addEventListener !='undefined') window.addEventListener('load',fn,false);
    else if(typeof document.addEventListener !='undefined') document.addEventListener('load',fn,false);
    else if(typeof window.attachEvent !='undefined') window.attachEvent('onload',fn);
    else{
        var oldfn=window.onload
        if(typeof window.onload !='function') window.onload=fn;
        else window.onload=function(){oldfn();fn();}
    }
}

Add and Remove an event!

This code is heavily based on the Quirksmode addEvent contest winner, John Resig, and his winning entry.

//------------------------------------
// addEvent
function addEvent(obj,type,fn){
    if(obj.addEventListener) obj.addEventListener(type,fn,false);
    else if(obj.attachEvent){
        obj["e"+type+fn]=fn;
        obj[type+fn]=function(){obj["e"+type+fn](window.event);}
        obj.attachEvent("on"+type,obj[type+fn]);
    }
}
 
//------------------------------------
// removeEvent
function removeEvent(obj,type,fn){
    if(obj.removeEventListener) obj.removeEventListener(type,fn,false);
    else if(obj.detachEvent){
        obj.detachEvent("on"+type,obj[type+fn]);
        obj[type+fn]=null;
        obj["e"+type+fn]=null;
    }
}

Cookies

//------------------------------------
// getExpDate
function getExpDate(days,hours,minutes){
    var expDate=new Date();
    if(typeof days=="number"&&typeof hours=="number"&&typeof hours=="number"){
        expDate.setDate(expDate.getDate()+parseInt(days));
        expDate.setHours(expDate.getHours()+parseInt(hours));
        expDate.setMinutes(expDate.getMinutes()+parseInt(minutes));
        return expDate.toGMTString();
    } else return "";
}
 
//------------------------------------
// getCookieVal
function getCookieVal(offset){
    var endstr=document.cookie.indexOf(";",offset);
    if(endstr==-1) endstr=document.cookie.length;
    return unescape(document.cookie.substring(offset,endstr));
}
 
//------------------------------------
// getCookie
function getCookie(name){
    var arg=name+"=";
    var alen=arg.length;
    var clen=document.cookie.length;
    var i=0;
    while(i<clen){
        var j=i+alen;
        if(document.cookie.substring(i,j)==arg) return getCookieVal(j);
        i=document.cookie.indexOf(" ",i)+1;
        if(i==0)break;
    }
    return "";
}
 
//------------------------------------
// setCookie
function setCookie(name,value,expires,path,domain,secure){
    document.cookie=name+"="+escape(value)+((expires)? "; expires="+expires : "")+((path)? "; path="+path : "")+((domain)? "; domain="+domain : "")+((secure)? "; secure" : "");
}
 
//------------------------------------
// deleteCookie
function deleteCookie(name,path,domain){
    if(getCookie(name)) document.cookie=name+"="+((path)? "; path="+path : "")+((domain)? "; domain="+domain : "")+"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

Highlights any input field that a user clicks on

//------------------------------------
// formEffects
function formEffects(){
    if(!gi('ContentW')) return;
    var areaDiv=gi('ContentW');
    var ut,rea;
    var INP=areaDiv.getElementsByTagName('input');
    var TAS=areaDiv.getElementsByTagName('textarea');
 
    for (var i=0;(ut=INP[i]);i++){
        addEvent(ut,'focus',oninputfocus);
        addEvent(ut,'blur',oninputblur);
    }
    for (var i=0;(rea=TAS[i]);i++){
        addEvent(rea,'focus',oninputfocus);
        addEvent(rea,'blur',oninputblur);
    }
}
 
//------------------------------------
// oninputfocus
function oninputfocus(evt){
    evt = (evt) ? evt : ((window.event) ? window.event : "");
    if (evt) var elem=giT(evt);
    if(elem)AddClass(elem,'Ffocus');
}
 
//------------------------------------
// oninputblur
function oninputblur(evt){
    evt = (evt) ? evt : ((window.event) ? window.event : "");
    if (evt) var elem=giT(evt);
    if(elem)RemoveClass(elem,'Ffocus');
}

Various functions to add, remove, or check for CSS classes on an object

//------------------------------------
// HasClass
function HasClass(el,cl){
    if((el.className===null)||(typeof el=='undefined')) return false;
    var classes=el.className.split(" ");
    for(i in classes){
        if(classes[i]==cl) return true;
    }
    return false;
}
 
//------------------------------------
// AddClass
function AddClass(el,cl){
    if((HasClass(el,cl))||(typeof el=='undefined')) return;
    el.className+=" "+cl;
}
 
//------------------------------------
// RemoveClass
function RemoveClass(el,cl){
    if(typeof el=='undefined')return;
    if(el.className===null)return;
    var classes=el.className.split(" ");
    var result=[];
    for(i in classes){
        if(classes[i] !=cl) result[result.length]=classes[i];
    }
    el.className=result.join(" ");
}

Hide or show an object using CSS

CSS

.S {visibility:visible;display:block;}
.H {visibility:hidden;display:none;}

Javascript

//------------------------------------
// H
function H(t){
    if(typeof t=='object') try t.className='H';
    catch(e){};
}
 
//------------------------------------
// S
function S(t){
    if(typeof t=='object') try t.className='S';
    catch(e){};
}

Get the element calling the function

//------------------------------------
// giT
function giT(evt){
    var elem;
    if (evt.target) elem = (evt.target.nodeType == 3) ? evt.target.parentNode : evt.target;
    else elem = evt.srcElement;
    return elem;
}

More Javascript Info:


http://www.askapache.com/javascript/my-favorite-javascript-2007.html#comments

Reader Comments

  1. Reynold P J ~April 28, 2009 @ 2:32 pm
    Anyone let me know how 2 reload a page from another page using javascript
  2. Gerry ~January 21, 2009 @ 12:25 pm
    i tried to insert this code below and it asked me for a :javascript code snippet. i am obviousily a beginner, can you help? Achat Auto Neuve
  3. Roel ~January 26, 2007 @ 4:29 pm
    Could you tell me how to get the script for "Highlights any input field that a user clicks on" working? I'm a rooky! I saved the script as a js, but it aint working at all.
  4. chris dahms ~January 7, 2007 @ 5:17 pm
    hey guys you should checkout mootools, it's a lightweight library that has functions for all these things... checkout element.js, styles.js and dom.js

Add Comment!

Leave a Reply

Your email address will not be published.


Google +

It's very simple - you read the protocol and write the code. -Bill Joy

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

Site Map | Contact Webmaster | Glossary | License and Disclaimer | Terms of Service |

↑ TOPMain