Forum Moderators: open
Let's take a look at the HTML part of this document:
<table id="myTable">We have a table and a div. The table has an ID (myTable) which will help us keep track of it in the JavaScript code. The div also has an ID (targetElement). This div is where we will write text dynamically...
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>Add</td>
</tr>
</table>
<div id="targetElement"></div>
function init() {This function is called when the page has loaded. We define two event handlers. Whenever the mouse is moved over our table (myTable), the function
document.getElementById('myTable').onmouseover = tellMe;
document.getElementById('myTable').onclick = expandTable;
oldElement = false;
}
tellMe is called. Whenever we click inside the table (myTable), the function expandTable is called. function tellMe() {This function does a couple things. First it sets a variable
currentElement = event.srcElement;
if(currentElement.innerText!= "Add" && currentElement.innerText!= "") {
if(oldElement) {
oldElement.style.backgroundColor = "";
}
oldElement = currentElement;
currentElement.style.backgroundColor = "#ffe";
parentRow = Math.floor(currentElement.parentNode.firstChild.innerText/5)+1;
document.getElementById('targetElement').innerHTML = ("Current row: " + parentRow + "<br>" + currentElement.tagName + " value: " + currentElement.innerText).replace(/\n/,"");
}
}
currentElement based on which element triggered the event. Next it resets the background color on the old element (if there is one), and sets a light yellow background on the element that triggered the event. Finally, it calculates which row the mouse moved over, and the text inside the table cell. This information is written to our div (targetElement). function expandTable() {Whenever we click inside the table, and only if it's the "Add" cell, this function is executed. First it also clears the background of the old element. Then it copies the current table row and appends it to the parent (= the table itself). Before adding, it iterates through the table cells to change the number sequence.
if(oldElement) {
oldElement.style.backgroundColor = "";
}
oldElement = false;
currentElement = event.srcElement;
if(currentElement.innerText == "Add") {
newFields = currentElement.parentNode.cloneNode(true);
for(i=0;i<5;i++) {
newFields.childNodes[i].innerText = (newFields.childNodes[i].innerText)*1 + 5;
}
currentElement.innerText = "";
currentElement.parentNode.parentNode.appendChild(newFields);
}
document.getElementById('targetElement').innerHTML = "";
}
Maybe it's not that useful of an example, but it shows some of the functionality that can be achieved by utilizing the powers of JavaScript. If you haven't dealt with nodes before, this is a good example to start with!