Ultimate Web Tips
your Wordpress, jQuery, PHP, MySQL, Linux and CSS guide to a successful website
Read more:

March 24th, 2011

Create an onclick function with jQuery from a string

jQuery, by Joakim Ling.

Let’s say you want to track all A tags with a specific href value with Google Analytics. This is quite simple and very useful if you want to see how many clicked on open a dialog, gallery etc.

My guess is that you already got jQuery included. If not, just include from Google into your header.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>

What we want to do is to add an onclick function event after document is loaded. But only to links that calls a specific function or page, so we need to check all A tags and check the value in href first.

We also need to create a function call from our string that we want to run, this string can be either saved in a database or somewhere in your HTML.

<script type="text/javascript">
var GA_func = "return _gaq.push(['_trackEvent', 'Gallery', 'Open']);";
var LinkValue = "javascript:openGallery();";
var clickFn = new Function(GA_func);
 
$(document).ready(function() {
	$('A').each(function() {
		if ($(this).attr('href') == LinkValue) {
			// the ".attr('onclick','')" will clear previous onclick action
			$(this).attr('onclick','').click(clickFn);
		}
	});
});
</script>

When we created the function call “new Function(string)”, we can stick that to any jQuery event. Quite useful when you’re running a page on a CMS and want to keep event as dynamic as possible. Took me a while to get my head around it though.

Ajax Form Pro

Create professional secure forms with captcha, realtime validation and php backend. Read more

Back Top

Club World Casinos
  • John

    Thanks for post