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 »
96 total  XML / RSS feed 

UTF8 encode/decode helper library

var $utf8 = {  
      
    encode : function (string) {  
        string = string.replace(/\r\n/g,"\n");  
        var utftext = "";  
  
        for (var n=0, k=string.length; n < k; n++) {  
            var c = string.charCodeAt(n);  
  
            if (c < 128) {  
                utftext += String.fromCharCode(c);  
            }  
            else if((c > 127) && (c < 2048)) {  
                utftext += String.fromCharCode((c >> 6) | 192);  
                utftext += String.fromCharCode((c & 63) | 128);  
            }  
            else {  
                utftext += String.fromCharCode((c >> 12) | 224);  
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);  
                utftext += String.fromCharCode((c & 63) | 128);  
            }  
        }  
        return utftext;  
    },  
  
    decode : function (utftext) {  
        var string = "";  
        var i = 0;  
        var c = c1 = c2 = 0;  
  
        while ( i < utftext.length ) {  
            c = utftext.charCodeAt(i);  
            if (c < 128) {  
                string += String.fromCharCode(c);  
                i++;  
            }  
            else if((c > 191) && (c < 224)) {  
                c2 = utftext.charCodeAt(i+1);  
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));  
                i += 2;  
            }  
            else {  
                c2 = utftext.charCodeAt(i+1);  
                c3 = utftext.charCodeAt(i+2);  
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));  
                i += 3;  
            }  
  
        }  
        return string;  
    }  
}

Never render the full layout in a Rails view when called via AJAX

Essential for degradable javascript, when one never knows if a view or partial is being called via XmlHttpRequest or not. Throw the below code in your ApplicationController (application.rb)

More info in this blog post

def render(*args)
        args.first[:layout] = false if request.xhr? and args.first[:layout].nil?
        super
end

Javascript Numbers Only

Restrict entering anything but numbers in a form field with javascript

javascript:
<SCRIPT TYPE="text/javascript">
<!--
// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}

//-->
</SCRIPT>


html
<FORM ACTION="../cgi-bin/mycgi.pl" METHOD=POST>
U.S. ZIP Code: 
  <INPUT NAME="dollar" SIZE=5 MAXLENGTH=5
   onKeyPress="return numbersonly(this, event)">
  <INPUT TYPE=SUBMIT VALUE="go">
</FORM>

Find element position relative to other elements

http://particletree.com/notebook/finding-element-positions/

scriptaculous requirements

For some strange reason, a hidden element that will be worked on by scriptaculous must have its display:none style inline, within the element, and not from a css class.

<div id="flash_box" class="flash_box" style="display:none;">
        <div id="fb_content" class="fb_content">
                <%= flash[:warning] %>
        </div>
        <span id="fb_close" class="fb_close" onclick="new Effect.BlindUp($('flash_box'), {duration:0.25})">
                Close This
        </span>
</div>


The div 'flash_box' only works with scriptaculous when
style="display:none;"

is used _inline_.

Escaping single quotes in a javascript literal string

When you need to include multiple nested single quotes within a string of javascript to be executed, escape single quotes with a back slash as needed.

Example from within an .rhtml template

hide_warning = "window.setTimeout('Effect.BlindUp($(\\'flash_box\\'), {duration:.3})', #{@warning_timeout ||= 8000})"


In this example, Double backslashes are required since the blackslash itself needs to be escaped and included within the string of js to be executed by windown.setTimeout().

programmatically firing object event using javascript

Simply call the event of the object.

<select id='element_id' onChange="some_javascript_func">

<a href="#" onclick="$('element_id').onchange();">


Note that this uses Prototype's $ function to find the element.

More details here:
http://tinyurl.com/2b45me

Insert in place without document.write

// http://www.sitepoint.com/blogs/2007/07/11/insert-in-place-without-documentwrite/

// So, given a syndication script with a fixed ID:
<script type="text/javascript" id="syndication" src="syndication.js"></script> 

// We can go from oldskool nastiness like this:
document.write('<p id="syndicated-content">Here is some syndicated content.</p>'); 

// To modern loveliness like this:

var newcontent = document.createElement('p'); 
newcontent.id = 'syndicated-content'; 
newcontent.appendChild(document.createTextNode('Here is some syndicated content.')); 
var scr = document.getElementById('syndication'); 
scr.parentNode.insertBefore(newcontent, scr); 

// We could even go a step further and remove the <script> ID, but in that case we would need a concrete method for identifying the specific element. We could do that by knowing its SRC:

var scripts = document.getElementsByTagName('script'); 
for(var i=0; i<scripts.length; i++) 
{ 
  if(scripts[i].src == 'http://www.mydomain.com/syndication.js') 
  { 
    //scripts[i] is the one 
    break; 
  } 
}

DomReady extension for prototype

This gives you a new event (onDOMReady).

Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    if (this._timer)  clearInterval(this._timer);
    
    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
},
  onDOMReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady.bind(this);
      
      if (document.addEventListener)
        document.addEventListener("DOMContentLoaded", domReady, false);
        
        /*@cc_on @*/
        /*@if (@_win32)
            document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
            document.getElementById("__ie_onload").onreadystatechange = function() {
                if (this.readyState == "complete") domReady(); 
            };
        /*@end @*/
        
        if (/WebKit/i.test(navigator.userAgent)) { 
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady(); 
          }, 10);
        }
        
        Event.observe(window, 'load', domReady);
        Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});


Example:

Event.onDOMReady(function(){  
alert('DOM is loaded!');  
});

Safari <label> fix

if (navigator.userAgent.indexOf('Safari') != -1) {
        window.addEventListener('load', function() {
                var lock = false;
                var labels = document.getElementsByTagName('label');
                for (var i = 0; i < labels.length; i++)
                        labels[i].addEventListener('click', function() {
                                var input = (this.htmlFor ? document.getElementById(this.htmlFor) : this.getElementsByTagName('input')[0]);
                                if (input && !lock) {
                                        input.focus();
                                        lock = true;
                                        input.click();
                                        lock = false;
                                }
                        });
        });
}

Load javascript function from returned ajax HTML

Problem - calling a function in <script> tags from dynamic ajax results does not get executed by the browser

Resolution - make a pixel image and call the function with the onload event in the image

<img src="some_image.jpg" onload="someFunction();">

Opening window/tab helper library for Mozilla

var $window = {
        open_in_new_tab: function(url){
                getBrowser().selectedTab = getBrowser().addTab(url);
        },

        open_in_same_tab: function(url){
                top.content.document.location = url;
        },

        open_as_popup: function(url){
                var mypopup = window.open(url,'popuppage','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=400,left=30,top=30');
                mypopup.focus();
        },

        focus: function(obj){
                obj.focus();
        },

        click : function(aEvent,url){
                if (aEvent.button == 2){
                        this.open_as_popup(url);
                }
                else if ((aEvent.ctrlKey) || (aEvent.button == 1) || (aEvent.metaKey)){
                        this.open_in_new_tab(url);
                } 
                else {
                        this.open_in_same_tab(url);
                        this.focus(window._content);
                        
                }
        }
}

Usage:
<toolbarbutton id="myid" label="my button"  class="toolbarbutton-1" onclick="$window.click(event,'http://localhost/');" />

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<myArray1.length;j++){
                // change this as you wish:
                alert(myArray1[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<myArray1.length;j++){
                // change this as you wish:
                alert(myArray1[j]['title']);
        }
}
</script>
<a href="#" onclick="test_createDB();">Create DB</a> | 
<a href="#" onclick="test_addRecord()">Simple Add Record</a> | 
<a href="#" onclick="test_addRecordParameterized()">Parameterized Add Record</a> | 
<a href="#" onclick="test_Select()">Simple Select</a> | 
<a href="#" onclick="test_SelectParameterized()">Parameterized Select</a> |

"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>
<a href="http://technorati.com/search/<txp:permlink />" rel="linkcount">View blog reactions</a>

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();
« Newer Snippets
Older Snippets »
96 total  XML / RSS feed