I'm having a problem with adding onClick events to <a> tags. The attribute is never added at all, but no errors are shown in the JavaScript console. I'm using Firefox 3.0.10.

Here's my code:

<html>
<head>
<script type="text/javascript">
function setAJAXAttributes() {
	var domain = new RegExp("(" + window.location.host + ")|(^\\/.*)|(^[\\w\\d]*\\.[\\w\\d]{2,})", "i");
	var links = document.getElementsByTagName("a");

	for (var i=0; i<links.length; i++) {
		if (domain.test(links[i].href)) {
			links[i].onClick = "getPage('" + links[i].href + "');";
			alert("Added onClick: " + links[i].href);
		}
		else
			links[i].target = "_blank";
	}
}
</script>
</head>
<body>

<a href="http://www.daniweb.com">DaniWeb</a><br/>
<a href="http://www.example.com/ajax/test.html">Testing absolute path</a><br/>
<a href="/ajax/test.html">Testing page relative parent path</a><br/>
<a href="test.html">Testing name path</a><br/>

<script type="text/javascript">setAJAXAttributes();</script>
</body>
</html>

I made sure that the conditional statement was working correctly by adding an alert to the onClick portion, and the alerts worked fine. However, the onClick event is never added, not on Firefox or IE7.

It also works fine if I change each <a> tag's href to javascript: getPage(); , but I don't want to change what shows in the status bar.

Hi there,

the onClick event, must be all in lowercase onclick :

links[i].[b]onclick[/b] = "getPage('" + links[i].href + "');";

Hmm, I tried that, but there's still the same problem. Any other thoughts?

Assign it as function:

links[i].onclick = function() { //Callback 
};

Like this:

links[i].onclick = function() { getPage( this.href ); 
};
commented: Great! Thanks! +1

Thanks! That worked perfectly. Tried that method earlier, but not in combination with all lowercase onclick .

Here is the line that is fixed:

links[i].onclick = function() { getPage(this.href); return false; };

+rep :)

Thank's again, itsjareds...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.