I'm new to Javascript. I want to add onclick events to table rows. I'm not using JQuery.
I loop thru the rows and use a closure to make sure I have the state of the outer function for each row. The looping works. Using alerts, I see the function being assigned for each iteration. But when I click the row, no alert is displayed. Below is the HTML and code that can be loaded.
Why are the table row events not working?
function example4() {
var table = document.getElementById("tableid4");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
var curRow = table.rows[i];
//get cell data from first col of row
var cell = curRow.getElementsByTagName("td")[0];
curRow.onclick = function() {
return function() {
alert("row " + i + " data=" + cell.innerHTML);
};
};
}
}
function init() {
example4();
}
window.onload = init;
Use loop to assign onclick handler for each table row in DOM. Uses Closure.
<table id="tableid4" border=1>
<tbody>
<tr>
<td>Item one</td>
</tr>
<tr>
<td>Item two</td>
</tr>
<tr>
<td>Item three</td>
</tr>
</tbody>
</table>
Task
Use loop to assign onclick handler for each table row in DOM. Use Closure.
function example4() {
let table = document.getElementById("tableid4");
let rows = table.rows;
for (let i = 0; i < rows.length; i++) {
// Using a closure in a modern way
((row, index) => {
row.addEventListener('click', () => {
alert(`row ${index} data=${row.querySelector('td').textContent}`);
});
})(rows[i], i);
}
}
window.addEventListener('DOMContentLoaded', example4);
<table id="tableid4" border="1">
<tbody>
<tr>
<td>Item one</td>
</tr>
<tr>
<td>Item two</td>
</tr>
<tr>
<td>Item three</td>
</tr>
</tbody>
</table>
However with let there is no need for a closure
function example4() {
let table = document.getElementById("tableid4");
let rows = table.rows;
for (let i = 0; i < rows.length; i++) { // the "let" does the job
rows[i].addEventListener('click', function() {
alert(`row ${i} data=${this.querySelector('td').textContent}`);
});
}
}
window.addEventListener('DOMContentLoaded', example4);
<table id="tableid4" border="1">
<tbody>
<tr>
<td>Item one</td>
</tr>
<tr>
<td>Item two</td>
</tr>
<tr>
<td>Item three</td>
</tr>
</tbody>
</table>
This brings me to a pet peeve of mine: looping eventListeners
If we delegate, the script is simpler and easier to read
const items = ["Item one", "Item two", "Item three"];
window.addEventListener('DOMContentLoaded', () => {
// create a table using an array. This can be as complex as needed depending on the data.
document.getElementById('container').innerHTML =
`<table id="tableid4" border="1">
<tbody>
${items
.map((item,i) => `<tr data-idx="${i}"><td>${item}</td></tr>`)
.join('')}
</tbody>
</table>`;
document.querySelector('#tableid4 tbody')
.addEventListener('click', (e) => {
const tgt = e.target.closest('tr');
if (!tgt) return; // not clicking in a row
alert(`row ${tgt.dataset.idx} data=${tgt.querySelector('td').textContent}`);
});
});
<div id="container"></div>
This was the canonical way in 2012
By using a closure (function() {...})(i), you're creating a new scope where the current value of i is passed and preserved in cnt for each iteration. This way, each click handler retains its own separate cnt value, which corresponds to the row index at the time the handler was created.
function example4() {
var table = document.getElementById("tableid4");
var rows = table.rows; // or table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
rows[i].onclick = (function() { // closure
var cnt = i; // save the counter to use in the function
return function() {
alert("row"+cnt+" data="+this.cells[0].innerHTML);
}
})(i);
}
}
window.onload = function() { example4(); }
@ParkerSuperstar suggested that the i in (i) is not needed.
for (var i = 0; i < rows.length; i++) {
rows[i].onclick = (function() {
var cnt = i;
return function() {
alert("row" + cnt + " data=" + this.cells[0].innerHTML);
}
})();
}
That is because the closure (function() {...})() is immediately invoked at each iteration of the loop. This creates a new execution context for each iteration.
Within this closure, var cnt = i; captures the current value of i for each iteration. Because a new closure is created for each iteration of the loop, each closure has its own execution context, and thus its own cnt variable.
I'm not quite sure why you're using a closure here, could you be a bit more elaborate?
The reason you're not seeing the desired alert is because within the onclick function, you're returning another function. I.e:
window.onload = function() {
return function() {
alert("Closure... why?");
};
};
Something like this won't really work because you're never calling the nested function... try it without using the closure, or comment explaining why you want a closure because you're explanation didn't make much sense to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With