Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
Showing 21-40 of 104 total

Dynamically adding XUL elements

var mylib = {
       appendXulEl : function(parentId,nodeName,attribs){
                var elem = document.getElementById(parentId);
                var node = document.createElement(nodeName);
                for (attrib in attribs) {
                        node.setAttribute(attrib, attribs[attrib]);
                }            
                elem.appendChild(node);
        }
}


Usage:
mylib.appendXulEl('BrowserToolbarPalette', 'toolbarbutton', {'id':'MY_BUTTON_ID', 'label':'label for my button', 'tooltiptext':'button tooltip', 'class':'toolbarbutton-1', 'onclick':'alert("test")', 'context':''})

Mozilla Preferences helper library


var $Prefs = {
        _getBranch : Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch),
        _getService : Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
                
        set : function(pref_name, pref_value) {
                var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
                str.data = pref_value.replace(/^\s*|\s*$/g,'');
                (this._getBranch).setComplexValue(pref_name, Components.interfaces.nsISupportsString, str);
        },
        
        get : function(pref_name){
                try{
                        return (this._getBranch).getComplexValue(pref_name,Components.interfaces.nsISupportsString).data;
                }
                catch(e){ return false;}
        },

        remove : function(pref_name){
                try{
                        (this._getBranch).clearUserPref(pref_name)
                }
                catch(e){}
        },
                
        remove_all : function(pref_name){
                try{
                        (this._getBranch).deleteBranch(pref_name,'')
                }
                catch(e){}
        },
                        
        branch : function(pref_name){
                var serialBranch = (this._getService).getBranch(pref_name+'.');
                return serialBranch.getChildList("",{});
        }
}

Sqlite helper library for Mozilla

var $sqlite = {
        storageService: [],
        mDBConn: [],
        
        _initService : function(file){
                var db = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile);
                db.append(file);
                this.storageService[file] = Components.classes["@mozilla.org/storage/service;1"].getService(Components.interfaces.mozIStorageService);
                this.mDBConn[file] = (this.storageService[file]).openDatabase(db);
                        
        },
        
        select : function(file,sql,param){
                if (this.storageService[file]== undefined){
                    this._initService(file);
                }
                var ourTransaction = false;
                if ((this.mDBConn[file]).transactionInProgress){
                        ourTransaction = true;
                        (this.mDBConn[file]).beginTransactionAs((this.mDBConn[file]).TRANSACTION_DEFERRED);
                }
                var statement = (this.mDBConn[file]).createStatement(sql);
                if (param){
                        for (var m=2, arg=null; arg=arguments[m]; m++) {
                                statement.bindUTF8StringParameter(m-2, arg);
                        }
                }
                try{
                        var dataset = [];
                        while (statement.executeStep()){
                                var row = [];
                                for(var i=0,k=statement.columnCount; i<k; i++){
                                        row[statement.getColumnName(i)] = statement.getUTF8String(i);
                                }
                                dataset.push(row);
                        }
                        // return dataset;  
                }
                finally {
                        statement.reset();
                }
                if (ourTransaction){
                        (this.mDBConn[file]).commitTransaction();
                }
        return dataset;      
        },
        
        
        cmd : function(file,sql,param){
                if (this.storageService[file] == undefined){
                            this._initService(file);
                }
                var ourTransaction = false;
                if ((this.mDBConn[file]).transactionInProgress){
                        ourTransaction = true;
                        (this.mDBConn[file]).beginTransactionAs((this.mDBConn[file]).TRANSACTION_DEFERRED);
                }
                var statement = (this.mDBConn[file]).createStatement(sql);
                if (param){
                        for (var m=2, arg=null; arg=arguments[m]; m++) {
                                statement.bindUTF8StringParameter(m-2, arg);
                        }
                }
                try{
                        statement.execute();
                }
                finally {
                        statement.reset();
                }
                if (ourTransaction){
                        (this.mDBConn[file]).commitTransaction();
                }
        }    

}

Usage:
<script language="javascript">
//some variables :
//assuming db file is in user's profile directory:
var myDBFile = 'mydb.sqlite';

// some example SQL queries:
var myCreateDBQuery = 'CREATE TABLE IF NOT EXISTS mybooks_tbl (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);';

var myInsertQuery = 'INSERT INTO mybooks_tbl(title) VALUES("book title1");';
var myInsertQueryParameterized = 'INSERT INTO mybooks_tbl(title) VALUES(?1);';

var mySelectQuery = 'SELECT id,title FROM mybooks_tbl';
var mySelectQueryParameterized = 'SELECT id,title FROM mybooks_tbl WHERE id = ?1 AND title = ?2';



// For anything other than SELECT statement, use $sqlite.cmd() :
 
// creating a DB:
function test_createDB(){
        $sqlite.cmd(myDBFile,myCreateDBQuery);
}

// simple add record:
function test_addRecord(){
        $sqlite.cmd(myDBFile,myInsertQuery);
}

// parameterized add record, add parameters as much as you want:        
function test_addRecordParameterized(){
        // for example, adding 3 records:
        for(var i = 1 ; i < 4; i++){
                $sqlite.cmd(myDBFile,myInsertQueryParameterized,'book title'+i+'');
        }
}

// for SELECT, use $sqlite.select() :

// simple select:
function test_Select(){
        var myArray1 = $sqlite.select(myDBFile,mySelectQuery);
        // Now you can loop through the array:
        for(var j=0;j'title']);
        }
}

// select with bound parameters, add parameters as much as you want:
function test_SelectParameterized(){
        var myArray1 = $sqlite.select(myDBFile,mySelectQueryParameterized,'1','book title1');
        // Now you can loop through the array:
        for(var j=0;j'title']);
        }
}

Create DB | 
Simple Add Record | 
Parameterized Add Record | 
Simple Select | 
Parameterized Select |

"Digg this page" XSS

// To include the nice little live-updated Digg widget

<script src="http://digg.com/tools/diggthis.js" type="text/javascript">script>

Technorati Link Count Widget for Textpattern

Technorati tracks when other bloggers link to your blog and this widget makes it possible for you to display the number of links on every blog post. We call them "reactions" to encourage readers to follow the conversation. To add the widget, copy and paste the code below into your blog's template.

<script src="http://embed.technorati.com/linkcount" type="text/javascript">script>
//technorati.com/search/<txp:permlink />" rel="linkcount">View blog reactions

Dynamically fetch JS

Code to dynamically download and include JS

/** include - including .js files from JS - [email protected] - 2005-02-09    **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
var hIncludes = null;
function include(sURI)
{
  if (document.getElementsByTagName)
  {
    if (!hIncludes)
    {
      hIncludes = {};
      var cScripts = document.getElementsByTagName("script");
      for (var i=0,len=cScripts.length; i < len; i++)
        if (cScripts[i].src) hIncludes[cScripts[i].src] = true;
    }
    if (!hIncludes[sURI])
    {
      var oNew = document.createElement("script");
      oNew.type = "text/javascript";
      oNew.src = sURI;
      hIncludes[sURI]=true;
      document.getElementsByTagName("head")[0].appendChild(oNew);
    }
  }
}

Factory patterns in Javascript


Suppose that you don't know the exact class that should be created until runtime. In the case of JavaScript, this may be due to browser differences. The best example of this today is in creating XMLHttp objects. A lot of times, you'll see code that looks like this:
if (typeof XMLHttpRequest != "undefined") {
    return new XMLHttpRequest();
} else if (typeof window.ActiveXObject != "undefined") {
    return new ActiveXObject("MSXML2.XMLHttp");
}

Clearly, you don't want to repeat this code every time you need to create a new XMLHttp object.

The factory pattern involves having a function (or an object with a method) that returns the appropriate object. Developers need not know which object is being returned since the interface will be the same no matter what. You need only call the function and know that the correct object will be returned. For example:
function XMLHttpFactory() {
}

XMLHttpFactory.createXMLHttp = function () {
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (typeof window.ActiveXObject != "undefined") {
        return new ActiveXObject("MSXML2.XMLHttp");
    }
} 

With this defined, developers can now use a single method call to create the object that will work for their environment:
var oXMLHttp = XMLHttpFactory.createXMLHttp();

Singelton in Javascript


function MyClass() {
   if (MyClass.caller != MyClass.getInstance) {
       throw new Error("There is no public constructor for MyClass.");
   }

   this.myproperty = "hello world";
}

MyClass.__instance__ = null;  //define the static property

MyClass.getInstance = function () {
    if (this.__instance__ == null) {
        this.__instance__ = new MyClass();
    }

    return this.__instance__;
}


Checking for the MyClass.caller != MyClass.getInstance in MyClass constructor will suppress the ability of the developer to do this:
var oMyObject = new MyClass();

Assertion in Javascript

Assertion is one of the commonly-used debugging techniques, it's used to ensure that an expression evaluates to true during execution, if the expression evaluates to false, this indicates a possible bug in code, JavaScript lacks a built-in assert function, but fortunately it's easy to write one, the following implementation throws an exception of type AssertException if the passed expression evaluates to false:

function AssertException(message) { this.message = message; }
AssertException.prototype.toString = function () {
    return 'AssertException: ' + this.message;
}

function assert(exp, message) {
    if (!exp) {
        throw new AssertException(message);
    }
}


Throwing an exception on its own isn't very useful, but when combined with a helpful error message or a debugging tool, you can detect the problematic assertion, you may also check whether an exception is an assertion exception by using the following snippet:

try {
    // ...
}
catch (e) {
    if (e instanceof AssertException) {
        // ...
    }
}


This function can be used in a way similar to C or Java:
assert(obj != null, 'Object is null');


If obj happens to be null, the following message will be printed in the JavaScript console in Firefox:
uncaught exception: AssertException: Object is null

A Caching XmlHttpRequest Wrapper



/* 
        XmlHttpRequest Wrapper
        Version 1.2.2
        29 Jul 2005 
        adamv.com/dev/
*/

var Http = {
        ReadyState: {
                Uninitialized: 0,
                Loading: 1,
                Loaded:2,
                Interactive:3,
                Complete: 4
        },
                
        Status: {
                OK: 200,
                
                Created: 201,
                Accepted: 202,
                NoContent: 204,
                
                BadRequest: 400,
                Forbidden: 403,
                NotFound: 404,
                Gone: 410,
                
                ServerError: 500
        },
                
        Cache: {
                Get: 1,
                GetCache: 2,
                GetNoCache: 3,
                FromCache: 4
        },
        
        Method: {Get: "GET", Post: "POST", Put: "PUT", Delete: "DELETE"},
        
        enabled: false,
        logging: false,
        _get: null,     // Reference to the XmlHttpRequest object
        _cache: new Object(),
        
        Init: function(){
                Http._get = Http._getXmlHttp()
                Http.enabled = (Http._get != null)
                Http.logging = (window.Logging != null);
        },
        
        _getXmlHttp: function(){
        /*@cc_on @*//*@if (@_jscript_version >= 5)
                try { return new ActiveXObject("Msxml2.XMLHTTP"); } 
                catch (e) {} 
                try { return new ActiveXObject("Microsoft.XMLHTTP"); } 
                catch (e) {} 
        @end @*/
                try { return new XMLHttpRequest();}
                catch (e) {}

                return null;
        },

/*
        Params:
                url: The URL to request. Required.
                cache: Cache control. Defaults to Cache.Get.
                callback: onreadystatechange function, called when request is completed. Optional.
                method: HTTP method. Defaults to Method.Get.
*/
        get: function(params, callback_args){   
                if (!Http.enabled) throw "Http: XmlHttpRequest not available.";
                
                var url = params.url;
                if (!url) throw "Http: A URL must be specified";
                                
                var cache = params.cache || Http.Cache.Get;
                var method = params.method || Http.Method.Get;
                var callback = params.callback;
                
                if ((cache == Http.Cache.FromCache) || (cache == Http.Cache.GetCache))
                {
                        var in_cache = Http.from_cache(url, callback, callback_args)

                        if (Http.logging){
                                Logging.log(["Http: URL in cache: " + in_cache]);
                        }

                        if (in_cache || (cache == Http.Cache.FromCache)) return in_cache;
                }
                
                if (cache == Http.Cache.GetNoCache)
                {
                        var sep = (-1 < url.indexOf("?")) ? "&" : "?"      
                        url = url + sep + "__=" + encodeURIComponent((new Date()).getTime());
                }
        
                // Only one request at a time, please
                if ((Http._get.readyState != Http.ReadyState.Uninitialized) && 
                        (Http._get.readyState != Http.ReadyState.Complete)){
                        this._get.abort();
                        
                        if (Http.logging){
                                Logging.log(["Http: Aborted request in progress."]);
                        }
                }
                
                Http._get.open(method, url, true);

                Http._get.onreadystatechange =  function() {
                        if (Http._get.readyState != Http.ReadyState.Complete) return;
                        
                        if (Http.logging){
                                Logging.log(["Http: Returned, status: " + Http._get.status]);
                        }

                        if ((cache == Http.Cache.GetCache) && (Http._get.status == Http.Status.OK)){
                                Http._cache[url] = Http._get.responseText;
                        }
                        
                        if (callback_args == null) callback_args = new Array();

                        var cb_params = new Array();
                        cb_params.push(Http._get);
                        for(var i=0;i<callback_args.length;i++)
                                cb_params.push(callback_args[i]);
                                
                        callback.apply(null, cb_params);
                }
                
                if(Http.logging){
                        Logging.log(["Http: Started\n\tURL: " + url + "\n\tMethod: " + method + "; Cache: " + Hash.keyName(Http.Cache,cache)])
                }
                
                Http._get.send(params.body || null);
        },
        
        from_cache: function(url, callback, callback_args){
                var result = Http._cache[url];
                
                if (result != null) {
                        var response = new Http.CachedResponse(result)
                        
                        var cb_params = new Array();
                        cb_params.push(response);
                        for(var i=0;i<callback_args.length;i++)
                                cb_params.push(callback_args[i]);
                                                        
                        callback.apply(null, cb_params);
                                
                        return true
                }
                else
                        return false
        },
        
        clear_cache: function(){
                Http._cache = new Object();
        },
        
        is_cached: function(url){
                return Http._cache[url]!=null;
        },
        
        CachedResponse: function(response) {
                this.readyState = Http.ReadyState.Complete
                this.status = Http.Status.OK
                this.responseText = response
        }    
}

Http.Init()

function json_response(response){
        var js = response.responseText;
        try{
                return eval(js); 
        } catch(e){
                if (Http.logging){
                        Logging.logError(["json_response: " + e]);
                }
                else{
                        alert("Error: " + e + "\n" + js);
                }
                return null;
        }
}

function getResponseProps(response, header){
        try {
                var s = response.getResponseHeader(header || 'X-Ajax-Props');
                if (s==null || s=="")
                        return new Object()
                else
                        return eval("o="+s)
        } catch (e) { return new Object() }
}



Caching Options
These options only make sense to use with the GET method. POST operations should not be cached.

Http.Cache.Get
Perform a normal request, and do not add the result to the local cache. Note: on IE, requesting the same URL via GET multiple times will cause IE to cache the result internally.
Http.Cache.GetCache
Perform a request and cache the result if sucessful. If the requested URL's response is already cached locally, do not perform the server request.
Http.Cache.GetNoCache
Perform a request and add a time-based variable to the querystring to force IE not to cache the result. The result is not placed in the local cache.
Http.Cache.FromCache
If the requested URL's response has already been cached, call the supplied callback on the locally cached version. Http.get will return true or false based on whether or not the response is in the cache.

The Timer class, for object-oriented timeouts

The problems with the setTimeout and setInterval functions provided in Javascript are twofold. First, you can't call a local object method without losing your scope, and second, you can't pass objects to the function, since the function call is implemented as a string.

The Timer class solves these difficulties by employing a static array to store the parent object and function arguments until the function is called.

// The constructor should be called with
// the parent object (optional, defaults to window).

function Timer(){
    this.obj = (arguments.length)?arguments[0]:window;
    return this;
}

// The set functions should be called with:
// - The name of the object method (as a string) (required)
// - The millisecond delay (required)
// - Any number of extra arguments, which will all be
//   passed to the method when it is evaluated.

Timer.prototype.setInterval = function(func, msec){
    var i = Timer.getNew();
    var t = Timer.buildCall(this.obj, i, arguments);
    Timer.set[i].timer = window.setInterval(t,msec);
    return i;
}
Timer.prototype.setTimeout = function(func, msec){
    var i = Timer.getNew();
    Timer.buildCall(this.obj, i, arguments);
    Timer.set[i].timer = window.setTimeout("Timer.callOnce("+i+");",msec);
    return i;
}

// The clear functions should be called with
// the return value from the equivalent set function.

Timer.prototype.clearInterval = function(i){
    if(!Timer.set[i]) return;
    window.clearInterval(Timer.set[i].timer);
    Timer.set[i] = null;
}
Timer.prototype.clearTimeout = function(i){
    if(!Timer.set[i]) return;
    window.clearTimeout(Timer.set[i].timer);
    Timer.set[i] = null;
}

// Private data

Timer.set = new Array();
Timer.buildCall = function(obj, i, args){
    var t = "";
    Timer.set[i] = new Array();
    if(obj != window){
        Timer.set[i].obj = obj;
        t = "Timer.set["+i+"].obj.";
    }
    t += args[0]+"(";
    if(args.length > 2){
        Timer.set[i][0] = args[2];
        t += "Timer.set["+i+"][0]";
        for(var j=1; (j+2)<args.length; j++){
            Timer.set[i][j] = args[j+2];
            t += ", Timer.set["+i+"]["+j+"]";
    }}
    t += ");";
    Timer.set[i].call = t;
    return t;
}
Timer.callOnce = function(i){
    if(!Timer.set[i]) return;
    eval(Timer.set[i].call);
    Timer.set[i] = null;
}
Timer.getNew = function(){
    var i = 0;
    while(Timer.set[i]) i++;
    return i;
}



Example usage:
function Ticker(){
    this.count = 0;
    this.timer = new Timer(this);
}
Ticker.prototype.tick = function(d){
    this.count+=d;
    window.status = ""+this.count;
    this.timer.setTimeout("tick", 1000, d);
}
                   
window.onload = function(){
    var ticker = new Ticker();
    ticker.tick(1);
}

AJAX Edit In Place With Prototype

// description of your code here

JS Source
/*
 * Edit In Place
 * http://josephscott.org/code/js/eip/
 *
 * Version: 0.2.0
 * License: http://josephscott.org/code/js/eip/license.txt
 */
EditInPlace = function() { };
EditInPlace.settings = function(set) {
        var settings = {
                id:                             false,
                save_url:               false,
                css_class:              'eip_editable',
                savebutton:             'eip_savebutton',
                cancelbutton:   'eip_cancelbutton',
                saving:                 'eip_saving',
                type:                   'text',
                orig_text:              false
        };

        for(var i in set) { settings[i] = set[i]; }

        return($H(settings));
};

EditInPlace.formField = function(set) {
        var field = '';
        set['orig_text'] = $(set['id']).innerHTML;

        if(set['type'] == 'text') {
                var size = set['orig_text'].length + 10;
                if(size >= 100) { size = 100; }
                if(set['size']) { size = set['size']; }

                field = '/>';
        }
        else if(set['type'] == 'textarea') {
                var cols = 50;
                if(set['cols']) { cols = set['cols']; }
                var rows = (set['orig_text'].length / cols) + 3;
                if(set['rows']) { rows = set['rows']; }

                field = '<span id="' + set['id'] + '_editor"><textarea id="'
                        + set['id'] + '_edit" class="' + set['css_class'] + '" name="'
                        + set['id'] + '_edit" rows="' + rows + '" cols="'
                        + cols + '">' + set['orig_text'] + 'textarea>';
        }

        return(field);
};

EditInPlace.formButtons = function(set) {
        return(
                '
/><span><input id="' + set['id'] + '_save" class="' + set['savebutton'] + '" type="button" value="SAVE" /> OR ' + '<input id="' + set['id'] + '_cancel" class="' + set['cancelbutton'] + '" type="button" value="CANCEL" />' + 'span></span>' ); }; EditInPlace.setEvents = function(set) { Event.observe( set['id'], 'mouseover', function() { Element.addClassName(set['id'], set['css_class']); }, false ); Event.observe( set['id'], 'mouseout', function() { Element.removeClassName(set['id'], set['css_class']); }, false ); Event.observe( set['id'], 'click', function() { Element.hide(set['id']); var field = EditInPlace.formField(set); var button = EditInPlace.formButtons(set); new Insertion.After(set['id'], field + button); Field.focus(set['id'] + '_edit'); Event.observe( set['id'] + '_save', 'click', function() { EditInPlace.saveChanges(set); }, false ); Event.observe( set['id'] + '_cancel', 'click', function() { EditInPlace.cancelChanges(set); }, false ); }, false ); }; EditInPlace.saveComplete = function(t, set) { $(set['id']).innerHTML = t.responseText; }; EditInPlace.saveFailed = function(t, set) { $(set['id']).innerHTML = set['orig_text']; Element.removeClassName(set['id'], set['css_class']); alert('Failed to save changes.'); }; EditInPlace.saveChanges = function(set) { var new_text = escape($F(set['id'] + '_edit')); $(set['id']).innerHTML = '<span class="' + set['saving'] + '">Saving ...span>'; Element.remove(set['id'] + '_editor'); Element.show(set['id']); var params = 'id=' + set['id'] + '&content=' + new_text; var ajax_req = new Ajax.Request( set['save_url'], { method: 'post', postBody: params, onSuccess: function(t) { EditInPlace.saveComplete(t, set); }, onFailure: function(t) { EditInPlace.saveFailed(t, set); } } ); }; EditInPlace.cancelChanges = function(set) { Element.remove(set['id'] + '_editor'); Element.removeClassName(set['id'], set['css_class']); Element.show(set['id']); } EditInPlace.makeEditable = function(args) { EditInPlace.setEvents(EditInPlace.settings(args)); }


HTML source
<html>
<head><title>Ajax Edit In Place (EIP) Exampletitle>







"example.html">Ajax Edit In Place (EIP) Example


"editme">AJAX edit in place like flickr.

"anotheredit">If you want room for more text you can use a textarea to edit instead.



PHP source
<?php
        $id = $_POST["id"];
        $content = $_POST["content"];
        print(htmlspecialchars($content));
?>

pop window desde un link

// esta es una forma muy buena de hacer un pop up desde un link

<a href="http://google.com/" onclick="window.open(this.href, 'popupwindow', 
  'width=400,height=300,scrollbars,resizable'); 
  return false;"
>

Making Javascript DOM a Piece of Cake with the graft() Function

graft() allows us to build chunks of DOM documents using really simple object notation. Graft() will feel very familiar to anyone who makes extensive use of the JSON format.

I’ll dive right into an example here and show graft in its simplest use. Suppose we have a DOM element somewhere in our document that we want to insert stuff into:

<div id="mycontentdiv">div>


If we wanted to insert a button into the above div element, we could use standard DOM in the following manner:

var mydiv = document.getElementById("mycontentdiv");
var btn = document.createElement("input");
btn.type = "button";
btn.value = "click me";
btn.onclick = function(){this.value="i have been clicked!";};
mydiv.appendChild(btn);


The above button example becomes the following using graft():

graft(
    document.getElementById("mycontentdiv"),
    ["input",
        {
            value:'click me',
            type:'button',
            onclick:'this.value="i have been clicked!";'
        }
    ]
);


// graft() function
// Originally by Sean M. Burke from interglacial.com
// Closure support added by Maciek Adwent

function graft (parent, t, doc) {

    // Usage: graft( somenode, [ "I like ", ['em',
    //               { 'class':"stuff" },"stuff"], " oboy!"] )

    doc = (doc || parent.ownerDocument || document);
    var e;

    if(t == undefined) {
        throw complaining( "Can't graft an undefined value");
    } else if(t.constructor == String) {
        e = doc.createTextNode( t );
    } else if(t.length == 0) {
        e = doc.createElement( "span" );
        e.setAttribute( "class", "fromEmptyLOL" );
    } else {
        for(var i = 0; i < t.length; i++) {
            if( i == 0 && t[i].constructor == String ) {
                var snared;
                snared = t[i].match( /^([a-z][a-z0-9]*)\.([^\s\.]+)$/i );
                if( snared ) {
                    e = doc.createElement(   snared[1] );
                    e.setAttribute( 'class', snared[2] );
                    continue;
                }
                snared = t[i].match( /^([a-z][a-z0-9]*)$/i );
                if( snared ) {
                    e = doc.createElement( snared[1] );  // but no class
                    continue;
                }

                // Otherwise:
                e = doc.createElement( "span" );
                e.setAttribute( "class", "namelessFromLOL" );
            }

            if( t[i] == undefined ) {
                throw complaining("Can't graft an undefined value in a list!");
            } else if(  t[i].constructor == String ||
                                    t[i].constructor == Array ) {
                graft( e, t[i], doc );
            } else if(  t[i].constructor == Number ) {
                graft( e, t[i].toString(), doc );
            } else if(  t[i].constructor == Object ) {
                // hash's properties => element's attributes
                for(var k in t[i]) {
                    // support for attaching closures to DOM objects
                    if(typeof(t[i][k])=='function'){
                        e[k] = t[i][k];
                    } else {
                        e.setAttribute( k, t[i][k] );
                    }
                }
            } else {
                throw complaining( "Object " + t[i] +
                    " is inscrutable as an graft arglet." );
            }
        }
    }

    parent.appendChild( e );
    return e; // return the topmost created node
}

function complaining (s) { alert(s); return new Error(s); }

IE PNG transparency fix

// Makes alpha channels in IE 5.5 and 6.0 work properly.

function correctPNG() {
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) {
      for(var i=0; i<document.images.length; i++){
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG"){
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "" + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\">" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}

Ajax Request Object Constructor

Wrapper function for constructing a request object.
Parameters:
reqType: The HTTP request type, such as GET or POST.
url: The URL of the server program.
asynch: Whether to send the request asynchronously or not.

function httpRequest(reqType,url,asynch) {

        // Mozilla-based browsers
        if (window.XMLHttpRequest) {
                request = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
                request = new ActiveXObject("Msxml2.XMLHTTP");
                if (!request) {
                        request = new ActiveXObject("Microsoft.XMLHTTP");
                }
        }
        
        // Request could still be null if neither ActiveXObject
        //   initialization succeeded
        if (request) {
                initReq(reqType,url,asynch);
        } else {
                alert("Your browser does not permit the use of all " +
                        "of this application's features!");
        }

}


Initialize a request object that is already constructed.

function initReq(reqType,url,asynch) {
        // Specify the function that will handle the HTTP response
        request.onreadystatechange = handleResponse;
        request.open(reqType,url,bool);
        request.send(null);
}

Date/Time Picker

// Pick Date/Time from popup window
// Looks for calendar icon "cal.gif"


//Javascript name: My Date Time Picker
//Date created: 16-Nov-2003 23:19
//Scripter: TengYong Ng
//Website: http://www.rainforestnet.com
//Copyright (c) 2003 TengYong Ng
//FileName: DateTimePicker.js
//Version: 0.8
//Contact: contact@rainforestnet.com
// Note: Permission given to use this script in ANY kind of applications if
//       header lines are left unchanged.

//Global variables
var winCal;
var dtToday=new Date();
var Cal;
var docCal;
var MonthName=["January", "February", "March", "April", "May", "June","July", 
        "August", "September", "October", "November", "December"];
var WeekDayName=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];    
var exDateTime;//Existing Date and Time

//Configurable parameters
var cnTop="200";//top coordinate of calendar window.
var cnLeft="500";//left coordinate of calendar window
var WindowTitle ="DateTime Picker";//Date Time Picker title.
var WeekChar=2;//number of character for week day. if 2 then Mo,Tu,We. if 3 then Mon,Tue,Wed.
var CellWidth=20;//Width of day cell.
var DateSeparator="-";//Date Separator, you can change it to "/" if you want.
var TimeMode=24;//default TimeMode value. 12 or 24

var ShowLongMonth=true;//Show long month name in Calendar header. example: "January".
var ShowMonthYear=true;//Show Month and Year in Calendar header.
var MonthYearColor="#cc0033";//Font Color of Month and Year in Calendar header.
var WeekHeadColor="#0099CC";//Background Color in Week header.
var SundayColor="#6699FF";//Background color of Sunday.
var SaturdayColor="#CCCCFF";//Background color of Saturday.
var WeekDayColor="white";//Background color of weekdays.
var FontColor="blue";//color of font in Calendar day cell.
var TodayColor="#FFFF33";//Background color of today.
var SelDateColor="#FFFF99";//Backgrond color of selected date in textbox.
var YrSelColor="#cc0033";//color of font of Year selector.
var ThemeBg="";//Background image of Calendar window.
//end Configurable parameters
//end Global variable

function NewCal(pCtrl,pFormat,pShowTime,pTimeMode)
{
        Cal=new Calendar(dtToday);
        if ((pShowTime!=null) && (pShowTime))
        {
                Cal.ShowTime=true;
                if ((pTimeMode!=null) &&((pTimeMode=='12')||(pTimeMode=='24')))
                {
                        TimeMode=pTimeMode;
                }            
        }    
        if (pCtrl!=null)
                Cal.Ctrl=pCtrl;
        if (pFormat!=null)
                Cal.Format=pFormat.toUpperCase();
        
        exDateTime=document.getElementById(pCtrl).value;
        if (exDateTime!="")//Parse Date String
        {
                var Sp1;//Index of Date Separator 1
                var Sp2;//Index of Date Separator 2 
                var tSp1;//Index of Time Separator 1
                var tSp1;//Index of Time Separator 2
                var strMonth;
                var strDate;
                var strYear;
                var intMonth;
                var YearPattern;
                var strHour;
                var strMinute;
                var strSecond;
                //parse month
                Sp1=exDateTime.indexOf(DateSeparator,0)
                Sp2=exDateTime.indexOf(DateSeparator,(parseInt(Sp1)+1));
                
                if ((Cal.Format.toUpperCase()=="DDMMYYYY") || (Cal.Format.toUpperCase()=="DDMMMYYYY"))
                {
                        strMonth=exDateTime.substring(Sp1+1,Sp2);
                        strDate=exDateTime.substring(0,Sp1);
                }
                else if ((Cal.Format.toUpperCase()=="MMDDYYYY") || (Cal.Format.toUpperCase()=="MMMDDYYYY"))
                {
                        strMonth=exDateTime.substring(0,Sp1);
                        strDate=exDateTime.substring(Sp1+1,Sp2);
                }
                if (isNaN(strMonth))
                        intMonth=Cal.GetMonthIndex(strMonth);
                else
                        intMonth=parseInt(strMonth,10)-1;       
                if ((parseInt(intMonth,10)>=0) && (parseInt(intMonth,10)<12))
                        Cal.Month=intMonth;
                //end parse month
                //parse Date
                if ((parseInt(strDate,10)<=Cal.GetMonDays()) && (parseInt(strDate,10)>=1))
                        Cal.Date=strDate;
                //end parse Date
                //parse year
                strYear=exDateTime.substring(Sp2+1,Sp2+5);
                YearPattern=/^\d{4}$/;
                if (YearPattern.test(strYear))
                        Cal.Year=parseInt(strYear,10);
                //end parse year
                //parse time
                if (Cal.ShowTime==true)
                {
                        tSp1=exDateTime.indexOf(":",0)
                        tSp2=exDateTime.indexOf(":",(parseInt(tSp1)+1));
                        strHour=exDateTime.substring(tSp1,(tSp1)-2);
                        Cal.SetHour(strHour);
                        strMinute=exDateTime.substring(tSp1+1,tSp2);
                        Cal.SetMinute(strMinute);
                        strSecond=exDateTime.substring(tSp2+1,tSp2+3);
                        Cal.SetSecond(strSecond);
                }    
        }
        winCal=window.open("","DateTimePicker","toolbar=0,status=0,menubar=0,fullscreen=no,width=195,height=245,resizable=0,top="+cnTop+",left="+cnLeft);
        docCal=winCal.document;
        RenderCal();
}

function RenderCal()
{
        var vCalHeader;
        var vCalData;
        var vCalTime;
        var i;
        var j;
        var SelectStr;
        var vDayCount=0;
        var vFirstDay;

        docCal.open();
        docCal.writeln("</span><span class="punct">"+</span><span class="constant">WindowTitle</span><span class="punct">+"</span><span class="string">");
        docCal.writeln("");
        docCal.writeln(""+FontColor+" vlink="+FontColor+">
"); vCalHeader="\"center\" valign=\"top\">\n";//MonthSelectorvCalHeader+="\n\n";vCalHeader+="";//CalendarheadershowsMonthandYearif(ShowMonthYear)vCalHeader+="\n";//WeekdayheadervCalHeader+=""+WeekHeadColor+">";for(i=0;i<7;i++){vCalHeader+="";}vCalHeader+="";docCal.write(vCalHeader);//CalendardetailCalDate=newDate(Cal.Year,Cal.Month);CalDate.setDate(1);vFirstDay=CalDate.getDay();vCalData="";for(i=0;i<vFirstDay;i++){vCalData=vCalData+GenCell();vDayCount=vDayCount+1;}for(j=1;j<=Cal.GetMonDays();j++){varstrCell;vDayCount=vDayCount+1;if((j==dtToday.getDate())&&(Cal.Month==dtToday.getMonth())&&(Cal.Year==dtToday.getFullYear()))strCell=GenCell(j,true,TodayColor);//Highlighttoday's date else { if (j==Cal.Date) { strCell=GenCell(j,true,SelDateColor); } else { if (vDayCount%7==0) strCell=GenCell(j,false,SaturdayColor); else if ((vDayCount+6)%7==0) strCell=GenCell(j,false,SundayColor); else strCell=GenCell(j,null,WeekDayColor); } } vCalData=vCalData+strCell; if((vDayCount%7==0)&&(j\n"; } } docCal.writeln(vCalData); //Time picker if (Cal.ShowTime) { var showHour; showHour=Cal.getShowHour(); vCalTime="\n\n"; docCal.write(vCalTime); } //end time picker docCal.writeln("\n
";//YearselectorvCalHeader+="\n
\n"; vCalHeader+=" \"javascript:winMain.Cal.DecYear();winMain.RenderCal()\">\""+YrSelColor+"\"><\"Verdana\" color=\""+YrSelColor+"\" size=2> "+Cal.Year+" \"javascript:winMain.Cal.IncYear();winMain.RenderCal()\">\""+YrSelColor+"\">>
"+Cal.GetMonthName(ShowLongMonth)+" "+Cal.Year+"
"+WeekDayName[i].substr(0,WeekChar)+"
'7' align='center'>"; vCalTime+="'text' name='hour' maxlength=2 size=1 style=\"WIDTH: 22px\" value="+showHour+" onchange=\"javascript:winMain.Cal.SetHour(this.value)\">"; vCalTime+=" : "; vCalTime+="'text' name='minute' maxlength=2 size=1 style=\"WIDTH: 22px\" value="+Cal.Minutes+" onchange=\"javascript:winMain.Cal.SetMinute(this.value)\">"; vCalTime+=" : "; vCalTime+="'text' name='second' maxlength=2 size=1 style=\"WIDTH: 22px\" value="+Cal.Seconds+" onchange=\"javascript:winMain.Cal.SetSecond(this.value)\">"; if (TimeMode==12) { var SelectAm =(parseInt(Cal.Hours,10)<12)? "Selected":""; var SelectPm =(parseInt(Cal.Hours,10)>=12)? "Selected":""; vCalTime+=""; } vCalTime+="\n
"); docCal.writeln(""); docCal.close(); } function GenCell(pValue,pHighLight,pColor)//Generate table cell with value { var PValue; var PCellStr; var vColor; var vHLstr1;//HighLight string var vHlstr2; var vTimeStr; if (pValue==null) PValue=""; else PValue=pValue; if (pColor!=null) vColor="bgcolor=\""+pColor+"\""; else vColor=""; if ((pHighLight!=null)&&(pHighLight)) {vHLstr1="color=
'red'>";vHLstr2="";} else {vHLstr1=">";vHLstr2="";} if (Cal.ShowTime) { vTimeStr="winMain.document.getElementById('"+Cal.Ctrl+"').value+=' '+"+"winMain.Cal.getShowHour()"+"+':'+"+"winMain.Cal.Minutes"+"+':'+"+"winMain.Cal.Seconds"; if (TimeMode==12) vTimeStr+="+' '+winMain.Cal.AMorPM"; } else vTimeStr=""; PCellStr="'center'>'verdana' size='2'"+vHLstr1+"'"+Cal.Ctrl+"').value='"+Cal.FormatDate(PValue)+"';"+vTimeStr+";window.close();\">"+PValue+""+vHLstr2+""; return PCellStr; } function Calendar(pDate,pCtrl) { //Properties this.Date=pDate.getDate();//selected date this.Month=pDate.getMonth();//selected month number this.Year=pDate.getFullYear();//selected year in 4 digits this.Hours=pDate.getHours(); if (pDate.getMinutes()<10) this.Minutes="0"+pDate.getMinutes(); else this.Minutes=pDate.getMinutes(); if (pDate.getSeconds()<10) this.Seconds="0"+pDate.getSeconds(); else this.Seconds=pDate.getSeconds(); this.MyWindow=winCal; this.Ctrl=pCtrl; this.Format="ddMMyyyy"; this.Separator=DateSeparator; this.ShowTime=false; if (pDate.getHours()<12) this.AMorPM="AM"; else this.AMorPM="PM"; } function GetMonthIndex(shortMonthName) { for (i=0;i<12;i++) { if (MonthName[i].substring(0,3).toUpperCase()==shortMonthName.toUpperCase()) { return i;} } } Calendar.prototype.GetMonthIndex=GetMonthIndex; function IncYear() { Cal.Year++;} Calendar.prototype.IncYear=IncYear; function DecYear() { Cal.Year--;} Calendar.prototype.DecYear=DecYear; function SwitchMth(intMth) { Cal.Month=intMth;} Calendar.prototype.SwitchMth=SwitchMth; function SetHour(intHour) { var MaxHour; var MinHour; if (TimeMode==24) { MaxHour=23;MinHour=0} else if (TimeMode==12) { MaxHour=12;MinHour=1} else alert("TimeMode can only be 12 or 24"); var HourExp=new RegExp("^\\d\\d$"); if (HourExp.test(intHour) && (parseInt(intHour,10)<=MaxHour) && (parseInt(intHour,10)>=MinHour)) { if ((TimeMode==12) && (Cal.AMorPM=="PM")) { if (parseInt(intHour,10)==12) Cal.Hours=12; else Cal.Hours=parseInt(intHour,10)+12; } else if ((TimeMode==12) && (Cal.AMorPM=="AM")) { if (intHour==12) intHour-=12; Cal.Hours=parseInt(intHour,10); } else if (TimeMode==24) Cal.Hours=parseInt(intHour,10); } } Calendar.prototype.SetHour=SetHour; function SetMinute(intMin) { var MinExp=new RegExp("^\\d\\d$"); if (MinExp.test(intMin) && (intMin<60)) Cal.Minutes=intMin; } Calendar.prototype.SetMinute=SetMinute; function SetSecond(intSec) { var SecExp=new RegExp("^\\d\\d$"); if (SecExp.test(intSec) && (intSec<60)) Cal.Seconds=intSec; } Calendar.prototype.SetSecond=SetSecond; function SetAmPm(pvalue) { this.AMorPM=pvalue; if (pvalue=="PM") { this.Hours=(parseInt(this.Hours,10))+12; if (this.Hours==24) this.Hours=12; } else if (pvalue=="AM") this.Hours-=12; } Calendar.prototype.SetAmPm=SetAmPm; function getShowHour() { var finalHour; if (TimeMode==12) { if (parseInt(this.Hours,10)==0) { this.AMorPM="AM"; finalHour=parseInt(this.Hours,10)+12; } else if (parseInt(this.Hours,10)==12) { this.AMorPM="PM"; finalHour=12; } else if (this.Hours>12) { this.AMorPM="PM"; if ((this.Hours-12)<10) finalHour="0"+((parseInt(this.Hours,10))-12); else finalHour=parseInt(this.Hours,10)-12; } else { this.AMorPM="AM"; if (this.Hours<10) finalHour="0"+parseInt(this.Hours,10); else finalHour=this.Hours; } } else if (TimeMode==24) { if (this.Hours<10) finalHour="0"+parseInt(this.Hours,10); else finalHour=this.Hours; } return finalHour; } Calendar.prototype.getShowHour=getShowHour; function GetMonthName(IsLong) { var Month=MonthName[this.Month]; if (IsLong) return Month; else return Month.substr(0,3); } Calendar.prototype.GetMonthName=GetMonthName; function GetMonDays()//Get number of days in a month { var DaysInMonth=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; if (this.IsLeapYear()) { DaysInMonth[1]=29; } return DaysInMonth[this.Month]; } Calendar.prototype.GetMonDays=GetMonDays; function IsLeapYear() { if ((this.Year%4)==0) { if ((this.Year%100==0) && (this.Year%400)!=0) { return false; } else { return true; } } else { return false; } } Calendar.prototype.IsLeapYear=IsLeapYear; function FormatDate(pDate) { if (this.Format.toUpperCase()=="DDMMYYYY") return (pDate+DateSeparator+(this.Month+1)+DateSeparator+this.Year); else if (this.Format.toUpperCase()=="DDMMMYYYY") return (pDate+DateSeparator+this.GetMonthName(false)+DateSeparator+this.Year); else if (this.Format.toUpperCase()=="MMDDYYYY") return ((this.Month+1)+DateSeparator+pDate+DateSeparator+this.Year); else if (this.Format.toUpperCase()=="MMMDDYYYY") return (this.GetMonthName(false)+DateSeparator+pDate+DateSeparator+this.Year); } Calendar.prototype.FormatDate=FormatDate;

Toggle Block Elements

// (Used for expanding and collapsing block elements. Good for hiding divs or expanding the divs for forms.)
// Link: Read more...
// In page:



function toggleLayer(whichLayer) 
{
        if (document.getElementById) 
        {
                // this is the way the standards work
                var style2 = document.getElementById(whichLayer).style;
                style2.display = style2.display? "":"none";
        }
        else if (document.all)
        {
                // this is the way old msie versions work
                var style2 = document.all[whichLayer].style;
                style2.display = style2.display? "":"none";
        }
        else if (document.layers)
        {
                // this is the way nn4 works
                var style2 = document.layers[whichLayer].style;
                style2.display = style2.display? "":"none";
        }
}

Print Page Form Button

// Creates a Print this Page button
// usage: document.write("
");
//printpage

var message = "Print this Page";
function printpage() {
window.print();  
}

Pop Up Window Generator

// Pop Up Window Generator
// (Parameters passed through URL string)
// Usage: Link Text

var win=null;

function NewWindow(mypage,myname,w,h,pos,infocus) {
        if (pos == "random") {
                myleft=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
                mytop=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
        }
        if (pos == "center") {
                myleft = (screen.width)?(screen.width-w)/2:100;
                mytop = (screen.height)?(screen.height-h)/2:100;
        } else if ((pos != 'center' && pos != "random") || pos == null) {
                myleft = 0;
                mytop = 20
        }
        settings = "width=" + w + ",height=" + h + ",top=" + mytop + ",left=" + myleft + ",scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no";
        win = window.open(mypage,myname,settings);
        win.focus();
}
« Newer Snippets
Older Snippets »
Showing 21-40 of 104 total