Loading jQuery in SVG

I’ve been reorganizing and ran across the Facebook page for the Technoanarchy I made as a part of a sci-fi story, The Revolution Will Be Televised. I made a logo that I think looks reasonably good:

Your browser has not displayed the image. Try the original source.

I thought a a script to animate the colors when someone clicked it would be entertaining. It’s pretty straightforward in jQuery:

$(document).click( function() {
  $( 'path, rect' ).each( function() {
    $(this).css({ fill : genColor() })
  } )
} )

Unfortunately, even though a new version is out, it still won’t load in SVG documents. I hacked out a couple workarounds to get it to load.

The first problem is the statement:

if ( !document.body ) {
  return setTimeout( jQuery.ready, 1 );
}

For a SVG, document.body is always null, so this check never passes and the file never loads. This is solved creating a faux body with:

document.__defineGetter__( 'body', function() { return document.documentElement } )

The next problem is a <div/> is created to test browser capabilities. SVG doesn’t have <div/> elements, so the result comes back null. This is fixed by filtering the input to createElement and creating a group in the place of a division:

( function() {
  var createElement = document.createElement
  document.createElement = function( name ) {
    if( name == 'div' ) {
      ns = document.documentElement.getAttribute( 'xmlns' )
      ret = document.createElementNS( ns, 'g' )
    } else {
       ret = createElement.apply( this, arguments )
    }
    return ret
  }
} )()

These need to be placed before the library inclusion or use this script that does the inclusion and loads jQuery:

<script type="text/javascript"
        xlink:href="http://will.tip.dhappy.org/lib/jquery/js"/>

Leave a Reply

Your email address will not be published. Required fields are marked *