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

xpath helper function

function $xpath(q,doc) { if (!doc || doc == '') {doc = document ; } return doc.evaluate(q, doc,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null); }

jQuery namespaced event binding/unbinding

// from a comment by Steven Bristol on errtheblog.com

I just wanted to share a really killer event handling tidbit:

Generally you do something like:

jQuery(’.class’).click(function(){//whatever});


Everyone knows this can be rewritten as:

jQuery(’.class’).bind(‘click’, function(){//whatever});


But sometimes you need to unbind something:

jQuery(’.class’).unbind(‘click’, function(){//});


The problem with this is that it will unbind all the click events, not just yours. So if multiple bits of javascript have a click event handler for ’.class’, unbinding removes them all. (This is because there is no way to identify an anonymous function.)

But jQuery is so good that there is a way to handle this: Namespacing your events:

jQuery(’.class’).bind(‘click.namespace’, function(){//}); 
jQuery(’.class’).unbind(‘click.namespace’);


or for reinitializing an element added via ajax:

jQuery(’.class’)unbind(‘click.namespace’).bind(‘click.namespace’, function(){//});

jQuery and Rails' respond_to

// Just throw this at the bottom of your application.js and you’re good to go: all jQuery ajax requests will trigger the wants.js block of your respond_to declaration, exactly like you’d expect. Enjoy.
// via: http://ozmm.org/posts/jquery_and_respond_to.html

jQuery.ajaxSetup({beforeSend’: function(xhr) {xhr.setRequestHeader(“Accept”,text/javascript”)} })

Javascript Bookmarklets

// various bookmarklets for cloning

javascript:var d=document,f='http://www.facebook.com/share',l=d.location,e=encodeURIComponent,p='.php?src=bm&v=4&i=1190041327&u='+e(l.href)+'&t='+e(d.title);1;try{if(!/^(.*\.)?facebook\.[^.]*$/.test(l.host))throw(0);share_internal_bookmarklet(p)}catch(z){a=function(){if(!window.open(f+'r'+p,'sharer','toolbar=0,status=0,resizable=0,width=626,height=436'))l.href=f+p};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else{a()}}void(0)


javascript:location.href='http://rickrolldb.com/entries/new?url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title);

Resize image to fit container

Resizes an image to fit into its container, depending on whether the width or height is longer, yet keeping the aspect ratio. Copied from a comment on sitepoint.com.

ffunction resizeImgOO(el) 
{ 
        function imgRatio()
        { 
                return (el.height / el.width); 
        } 
        function holderRatio()
        { 
                return (el.offsetParent.offsetHeight / el.offsetParent.offsetWidth); 
        } 
        function fitToContainer()
        { 
                if(imgRatio>holderRatio) 
                { 
                        el.height = el.offsetParent.offsetHeight; 
                } 
                else 
                { 
                        el.width = el.offsetParent.offsetWidth;   
                } 
        }
        
        this.imgRatio = imgRatio; 
        this.holderRatio = holderRatio; 
        this.resize = fitToContainer; 
}
var img = new resizeImgOO(document.getElementById('yourImgId'));
img.resize();

Walk Google Maps Dom and pick out image tiles

// Elliot wrote this to grab google maps image tiles.

  m = document.getElementById("map_canvas");
      gold = m.childNodes[0].childNodes[0].childNodes[1];
      list = gold.getElementsByTagName('img');
      a = new Array(list.length);
      for (var i = 0; i < list.length; i++)
      {
        a[i] = list[i].getAttribute('src');
      }
      alert(data);

JavaScript Roll Overs

// JavaScript roll overs

<script type="text/javascript">

script>

// html code
<a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image1','','2.png',1)"><img src="1.png" name="Image1" width="155" height="71" border="0" id="Image1" />a>

javascript phone regex

339-4248
339-42-48
339 42 48
339 4248
3394248
(095) #phone#
(095)#phone#
+7 (095) #phone#
+7 (095)#phone#
+7(095) #phone#
+7(095)#phone#

/^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/

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