Gorgo.Live.ToString()

Mariusz, Gorzoch tech Blog

Extending onClick HTML element object thru Javascript without use of attachEvent method

leave a comment »

Today I came across task where I needed to extend or maybe I should say replace already defined “onClick” event with new handler performing the same think with was doing previous with the extension of calling special custom function.

So we start with element definition like that:

<a href=”http://wp.pl” onClick=”Alert(‘Orginal handler’);return false”/>

now, as I can not touch the source which generated this line I needed to find a way to inject my function to onClick event keeping somehow current handler in place. Please notice here “return false” on the end of OnClick event which causing that if you go for “attachEvent” method, then your method still will not be called.

On the end I manager to do so, by the script (it is performing this operation for all “A” elements on the page):

<html>
<head>
<script language="Javascript">
function CorrectOnClick()
{
    var hrefs = document.getElementsByTagName("a");
    for(var i=0;i<hrefs.length;i++)
    {
        var strFun  = ""+hrefs[i].onclick;
        strFun = strFun.substring(strFun.indexOf("{")-1);
        hrefs[i].onclick = function ExtendedOnClik() {
                                                    alert("hi");
                                                    eval(strFun);
                                                }

    }
}
</script>
</head>
<body onLoad="CorrectOnClick()">
<a href="http://wp.pl" onClick="alert(this.href);return false;">wp.pl</a>
<a href="http://onet.pl" onClick="alert(this.href);return false;">onet.pl</a>
<a href="http://tvn24.pl" onClick="alert(this.href);return false;">tvn24.pl</a>
<a href="http://wykop.pl" onClick="alert(this.href);return false;">wykop.pl</a>
</body>

The trick is to get onClick definition and switch it with new one, which will do additional stuff and on the end call original handler.

ps. If you get interested what I needed this for, then I needed this to implement Omniture file download tracking on SharePoint site. “A” elements get generated by SharePoint core function and there is no way to change how they are doing this (and even if I could I don’t think I would go for that). On the other hand “Omniture” requires peace of code to track file downloads, so I needed to make those two work together somehow… and I think I did it.

Advertisements

Written by Mariusz Gorzoch

7 January 2010 at 12:03

Posted in Bez kategorii

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: