There are several improvements that can be made to this script.
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].onclick = function() {alert('I have been clicked')};
}
A completely new function is assigned to each onclick event. It uses less resources to have only the one function, and to assign to the onclick event a reference to that function.
[color="green"]function linkClickHandler() {
alert('I have been clicked');
}[/color]
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++) {
links[i].onclick = [color="green"]linkClickHandler[/color];
}
Calculate the length outside of the for loop. That way it doesn’t need to be calculated over and over again whenever the for loop loops around again.
Also, using += 1 instead of ++ makes it easier for you to specify different types of increments later on.
function linkClickHandler() {
alert('I have been clicked');
}
var links = document.getElementsByTagName("a");
[color="green"]var linksLen = links.length;[/color]
for (var i = 0; i < [color="green"]linksLen; i += 1[/color]) {
links[i].onclick = linkClickHandler;
}
Having var assignments scattered throughout the code is not a good idea. Always ensure that var assignments are at the start of a function or block of code.
function linkClickHandler() {
alert('I have been clicked');
}
[color="green"]var links = document.getElementsByTagName("a");
var linksLen = links.length;
var i;[/color]
for (i = 0; i < linksLen; i += 1) {
links[i].onclick = linkClickHandler;
}
You can (and should) combine multiple var statements to just one comma-separated var statement.
function linkClickHandler() {
alert('I have been clicked');
}
[color="green"]var links = document.getElementsByTagName("a"),
linksLen = links.length,
i;[/color]
for (i = 0; i < linksLen; i += 1) {
links[i].onclick = linkClickHandler;
}
Finally, instead of assigning onclick events to every single link on the page, you can instead monitor all clicks on the page, and take action when the click occurs on a link.
The benefit of this is that only one event handler is being added to the page.
document.body.onclick = function (evt) {
evt = evt || window.event;
var targ = evt.target || evt.srcElement;
if (targ.nodeType === 3) { // handle Opera bug
targ = targ.parentNode;
}
if (targ.nodeType === 1 && targ.nodeName === 'A') {
alert('I have been clicked');
}
}
That might be reaching too far beyond what you’re being taught though.