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">

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] %>
        
="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('

Here is some syndicated content.

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