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

jQuery namespaced event binding/unbinding

// from a comment by Steven Bristol on

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

Generally you do something like:


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(){//}); 

or for reinitializing an element added via ajax:

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

Find element position relative to other elements

Insert in place without document.write


// 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:

Here is some syndicated content.

'); // To modern loveliness like this: var newcontent = document.createElement('p'); = '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 == '') { //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)