The following code snippet is needed to capture html links for my site. Although, it seems to work, I wish to have an explanation so that I may improve upon it. Can someone give me a quick summary of what’s happening in this code? I don’t especially understand the while statement that uses this variable ‘link’. What is ‘link’? A dummy variable of some sort like you would use in a dictionary or map iteration? Also, why use document.links[0]?
if (document.links){
if (document.links[0]){
var links = document.links, link, k=0;
while(link=links[k++]) {
link.onclick = linkCapture;
}
}
}
function linkCapture() {
this.parent = this.parentNode;
eventCapture('Link Click','Page Tag',this.name,this.href);
}
The browser supports the property:
There is at least one link:
Standard initialization
For every run through the loop, set link to the next element, then increment k. Exit the loop when the current
links[k]is falsy (probably because we’ve passed the last element).Set the onclick property to linkCapture.
This really isn’t great code to begin with. You could write the whole thing using jQuery like:
As a bonus, you wouldn’t risk overwriting an existing
onclickproperty.