It still amazes me how software such as Drupal can solve huge problems very easily but sometimes they make little problems that should be very simple, way more complex. Case in point: adding javascript to onlick events in a link when using the Drupal built-in l() function.
The l function is pretty handy; you can easily create links, add attributes to those links such as css classes or titles, etc. Attributes are passed as an array in the options parameter. Attributes are run through Drupal's check_plain function which html encodes your data and prevents cross scripting vulnerabilities. The problem is that if you want to pass javascript with a single quote in it for example, it gets encoded and renders your javascript useless.
I wanted to add some click tracking with Google Analytics using their events tracking code. Their tracking code looks something like this:
<a href="http://somewebsite.com" onClick="_gat._getTrackerByName()._trackEvent('Website', 'http://somewebsite.com', 'Top links');">Visit website</a>
So the Drupal version should be something like:
<?php print l('Visit website', 'http://somewebsite.com', array('attributes' => array('onclick' = "_gat._getTrackerByName()._trackEvent('Website', 'http://somewebsite.com', 'Top links');"))); ?>
Unfortunately, the single quotes get encoded which messes up the javascript. After monkeying with this for a while, I decided to just pull out the l function (creatively called l2) and put it into my theme's template.php file. It calls the drupal_attributes function which I pull out as well. In my custom drupal_attributes function (which I name drupal_attributes2), I override the check_plain when the key is equal to onclick. I realize this is not an ideal solution and has some risk, but I am not sure what a better solution is.
Argh, if there's a better way to do this, please let me know.