I just developed a little code to create a 24×60 table. I want to print the id of each <td> on mouseover:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
table {
background-color:blue;
}
td {
width: 2px;
height: 2px;
background-color:red;
}
</style>
</head>
<body>
<table id="time-table"></table>
<script type="text/javascript">
var table = document.getElementById( "time-table" );
for ( var r = 0; r < 24; r++ ) {
var row = document.createElement( "tr" );
for ( var c = 0; c < 60; c++ ) {
var td = document.createElement( "td" );
td.id = "td-" + r + "-" + c;
td.onmouseover = function ( e ) {
console.log( this.id );
}
row.appendChild( td );
}
table.appendChild( row );
}
</script>
</body>
</html>
The code works, but now I’m concerned if it is optimized? Am I creating 1440 event handling functions in the nested loops? Or is the JavaScript interpreter smart enough to only create one function and assign it to 1440 <td> elements?
No, JavaScript won’t to any optimizations (well, maybe some implementations do, but you should not rely on that). You are really creating that many functions.
Better define the function once and reuse it:
Or consider to use event delegation, that is, binding the handler to an ancestor of the cells:
This works, since events bubble up the DOM tree and might even better performance-wise in some browsers.
A good resource to learn about event handling are the articles at quirksmode.org.