Table and mouse rollover effect (hover) - javascript

I have this table:
<table border="1">
<tr>
<td></td>
<td>Banana</td>
<td>Orange</td>
<td>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td>1:1</td>
<td>1:2</td>
<td>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td>2:1</td>
<td>1:1</td>
<td>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td>1:3</td>
<td>2:1</td>
<td>1:1</td>
</tr>
and CSS:
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
What I want to do, is when I for example point my mouse on 1:3 table cell, it should highlight together with Banana and Plum cells.
Any easy way to do it?
Here's fiddle:
http://jsfiddle.net/CZEJT/

If you dont mind a bit of Javascript in there to ensure compatibility, take a look at this JSFiddle
HTML:
<table>
<tr>
<th></th><th>50kg</th><th>55kg</th><th>60kg</th><th>65kg</th><th>70kg</th>
</tr>
<tr>
<th>160cm</th><td>20</td><td>21</td><td>23</td><td>25</td><td>27</td>
</tr>
<tr>
<th>165cm</th><td>18</td><td>20</td><td>22</td><td>24</td><td>26</td>
</tr>
<tr>
<th>170cm</th><td>17</td><td>19</td><td>21</td><td>23</td><td>25</td>
</tr>
<tr>
<th>175cm</th><td>16</td><td>18</td><td>20</td><td>22</td><td>24</td>
</tr>
</table>
CSS:
table {
border-spacing: 0;
border-collapse: collapse;
overflow: hidden;
z-index: 1;
}
td, th, .ff-fix {
cursor: pointer;
padding: 10px;
position: relative;
}
td:hover::after,
.ff-fix:hover::after {
background-color: #ffa;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
}
tr:hover{
background-color: #ffa;
}
}
JS:
function firefoxFix() {
if ( /firefox/.test( window.navigator.userAgent.toLowerCase() ) ) {
var tds = document.getElementsByTagName( 'td' );
for( var index = 0; index < tds.length; index++ ) {
tds[index].innerHTML = '<div class="ff-fix">' + tds[index].innerHTML + '</div>';
};
var style = '<style>'
+ 'td { padding: 0 !important; }'
+ 'td:hover::before, td:hover::after { background-color: transparent !important; }'
+ '</style>';
document.head.insertAdjacentHTML( 'beforeEnd', style );
};
};
firefoxFix();

below is an example from one of my sites (css):
/*when hover over shape 5 dim shape 5*/
#shape5{
opacity:1.0;
filter:alpha(opacity=100);}
#shape5:hover{
opacity:0.4;
filter:alpha(opacity=40);}
/*When hoverover text5 dim shape 5!*/
#text5:hover + #shape5{opacity:0.4;
filter:alpha(opacity=40);}
Hope that helps!!
Oh Also view: How to affect other elements when a div is hovered

would you like something like this?
unfortunately it would be necessary some javascript
HTML
<table border="1">
<tr>
<td></td>
<td id='1'>Banana</td>
<td id='2'>Orange</td>
<td id='3'>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td class='o1'>1:1</td>
<td class='o2'>1:2</td>
<td class='o3'>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td class='o1'>2:1</td>
<td class='o2'>1:1</td>
<td class='o3'>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td class='o1'>1:3</td>
<td class='o2'>2:1</td>
<td class='o3'>1:1</td>
</tr>
</table>
JAVASCRIPT
var cells1 = $('.o1');
cells1.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#1').css({background: '#ddd'})
})
cells1.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#1').css({background: 'none'})
})
var cells2 = $('.o2');
cells2.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#2').css({background: '#ddd'})
})
cells2.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#2').css({background: 'none'})
})
var cells3 = $('.o3');
cells3.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#3').css({background: '#ddd'})
})
cells3.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#3').css({background: 'none'})
})
CSS
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}

Try this:
Fiddle
Without changing your html structure or adding any third party library:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i++) {
var elem = document.getElementsByTagName('td')[i];
elem.addEventListener('mouseover', function () {
var text = this.innerHTML;
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
if (elem2.innerHTML == text) {
elem2.style.background = 'red';
}
}
}, false);
elem.addEventListener('mouseout', function () {
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
var text = this.innerHTML;
if (elem2.innerHTML == text) {
elem2.style.background = 'none';
}
}
}, false);
}
}, false);
</script>

I apologise that my answer is only in pseudo code, however I would approach this problem by using javascript (most possibly Jquery). I hope this makes sense...
<table id="tbl"> - so I would give the table an ID
<td onHover="changeHeaderColummns(this)"></td> - then on each of the columns have a jsMethod that fires.
<script>
changeHeaderColumsn(col)
{
var colIndex = col.Index; //get the current column index
var row = GetHeaderRow(); // get the header row
highLightColumn(row, colIndex); //change the colour of the cell
//with the same index in the header
row = getCurrentRow(col.RowIndex); //now get the current row
highlightColumn(row, 0); //change the colour of the cell
//with the index of 0
}
getHeaderRow()
{
return getRow(0);
}
getRow(rowIndex)
{
var table = document.getElementByID("tbl);
return table.rows[rowIndex];
}
highlightColumn(row, colIndex)
{
row[colIndex].style.backgroundcolor = "red";
}

for highlight columns you must use js like this jsfiddler. It's work with jQuery ;)
With code

Using jquery
fiddle: http://jsfiddle.net/itsmikem/CZEJT/12/
Option 1: highlights the cell and just the named fruit cells
$("td").on({
"mouseenter":function(){
$(this).closest("tr").find("td:first-child").css("background","#f99");
var col = $(this).index();
$(this).closest("table").find("tr:first-child").find(String("td:nth-child(" + (col + 1) + ")")).css("background","#f99");
$(this).css("background","#f00");
},
"mouseleave":function(){
$(this).closest("table").find("td,tr").css("background","none");
}
});
Option 2: highlights entire rows and columns that intersect the hovered cell
$("td").on({
"mouseenter": function () {
$(this).closest("tr").css("background", "#f99");
var col = $(this).index();
var myTable = $(this).closest("table");
var rows = $(myTable).find("tr");
$(rows).each(function (ind, elem) {
var sel = String("td:nth-child(" + (col + 1) + ")");
$(this).find(sel).css("background", "#f99");
});
$(this).css("background", "#f00");
},
"mouseleave": function () {
$(this).closest("table").find("td,tr").css("background", "none");
}
});

Related

Setting bg color with jQuery doesn't override existing one

I have a table that I use jQuery to color even and odd rows mainly because I want the user to chose which color he wants from few selections in form
But when I setup bgcolor of a table in css, the jQuery script won't work.
Below is the code to change the colors (jsfiddle https://jsfiddle.net/sh7cgaz4/)
It stops working when adding to the css, eg:
table,th,td {
background-color: red;
}
here is the fiddle when it stops working: https://jsfiddle.net/8g7wn0ov/
$(function() {
var colors = [{
display: "jasny żółty",
value: "ffffcc"
}, {
display: "jasny niebieski",
value: "ccffff"
}, {
display: "jasny zielony",
value: "ccffcc"
}, {
display: "szary",
value: "cccccc"
}, {
display: "biały",
value: "ffffff"
}];
var options = ['<option value="">wybierz kolor</option>'];
for (var i = 0; i < colors.length; i++) {
options.push('<option value="');
options.push(colors[i].value);
options.push('">');
options.push(colors[i].display);
options.push('</option>');
}
$('#koloryparzyste').html(options.join('')).change(function() {
var val = $(this).val();
if(val){
$('.parzyste').css('backgroundColor', '#' + val);
}
});
var options = ['<option value="">wybierz kolor</option>'];
for (var i = 0; i < colors.length; i++) {
options.push('<option value="');
options.push(colors[i].value);
options.push('">');
options.push(colors[i].display);
options.push('</option>');
}
$('#kolorynieparzyste').html(options.join('')).change(function() {
var val = $(this).val();
if (val) {
$('.nieparzyste').css('backgroundColor', '#' + val);
}
});
Your issue is that you are setting the css background colour on the table,th,td but in your javascript, you're only updating the tr (.nieparzyste / .parzyste which is a class on the tr).
As a td sits inside or "on top" of a tr the td colour overrides the tr colour.
You can fix this by setting the "default" (in the css) colour only on the tr, or by changing the jquery to also update the td.
Snippet using tr colour:
$(function() {
var colors = [{
display: "jasny żółty",
value: "ffffcc"
}, {
display: "jasny niebieski",
value: "ccffff"
}, {
display: "jasny zielony",
value: "ccffcc"
}, {
display: "szary",
value: "cccccc"
}, {
display: "biały",
value: "ffffff"
}];
var options = ['<option value="">wybierz kolor</option>'];
for (var i = 0; i < colors.length; i++) {
options.push('<option value="');
options.push(colors[i].value);
options.push('">');
options.push(colors[i].display);
options.push('</option>');
}
$('#koloryparzyste').html(options.join('')).change(function() {
var val = $(this).val();
if (val) {
$('.parzyste').css('backgroundColor', '#' + val);
}
});
var options = ['<option value="">wybierz kolor</option>'];
for (var i = 0; i < colors.length; i++) {
options.push('<option value="');
options.push(colors[i].value);
options.push('">');
options.push(colors[i].display);
options.push('</option>');
}
$('#kolorynieparzyste').html(options.join('')).change(function() {
var val = $(this).val();
if (val) {
$('.nieparzyste').css('backgroundColor', '#' + val);
}
});
});
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
text-align: center;
}
table tr {
background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="prawy">
<table id="kolorwa">
<tr class="parzyste">
<th>Lp.</th>
<th>Imię</th>
<th>Nazwisko</th>
<th>Stanowisko</th>
<th>Data zatrudnienia</th>
<th>Ilość dni urlopowych</th>
</tr>
<tr class="nieparzyste">
<td>1</td>
<td>Barbar</td>
<td>Sznuk</td>
<td>Dział Hr</td>
<td>11.06.2002</td>
<td>1</td>
</tr>
<tr class="parzyste">
<td>2</td>
<td>Tomasz</td>
<td>Kopyra</td>
<td>Pracwnik Produkcji</td>
<td>11.06.2005</td>
<td>11</td>
</tr>
<tr class="nieparzyste">
<td>3</td>
<td>Tomasz</td>
<td>Bukowski</td>
<td>Pracwnik Produkcji</td>
<td>02.01.2007</td>
<td>10</td>
</tr>
<tr class="parzyste">
<td>4 </td>
<td>Janusz</td>
<td>Tracz</td>
<td>Kierownik</td>
<td>21.06.2007</td>
<td>3</td>
</tr>
<tr class="nieparzyste">
<td>5</td>
<td>Grzegorz</td>
<td>Kowalski</td>
<td>Dyrektor</td>
<td>29.09.1999</td>
<td>15</td>
</tr>
</table>
<form name="koloryparzyste">Tu zmienisz kolory parzyste<br>
<select id="koloryparzyste"></select>
</form>
<form name="kolorynieparzyste">Tu zmienisz kolory nieparzyste<br>
<select id="kolorynieparzyste"></select>
</form>
</div>
you are looking for background-color instead of backgroundColor
$('.nieparzyste').css('background-color', '#' + val);

jQuery How to change class for each table data row?

I have table, with data, and i need for td:eq(4) change class, and box for baghround.
I have this code:
$('tr').each(function () {
var rowCol = $(this);
rowCol.find('td:eq(4)').each(function () {
var rowValue = parseFloat($(this).text());
console.log(rowValue === 0)
if (rowValue > 1) {
$('.defects').addClass('def').removeClass('defects');
} else {
$('.def').addClass('defects').removeClass('def');
}
});
});
.defects {
background: #e74c3c;
color: #fff;
padding: 3px;
border-radius: 6px;
}
And if at this td i have value more then 1, i add bg red box.
But nox, something went wrong.
Without seeing your html, I can only guess about how it looks based on your code, but try this:
$('tr').each(function() {
var rowCol = $(this);
rowCol.find('td:eq(4)').each(function() {
var mytd = $(this);
var rowValue = parseFloat($(this).text());
console.log(rowValue === 0)
if (rowValue > 1) {
mytd.addClass('def').removeClass('defects');
} else {
mytd.addClass('defects').removeClass('def');
}
});
});
first of, I'm assigning your td:eq(4) to a variable var mytd = $(this);.
then I'm replacing $('.defects') with mytd
Code
$('tr').each(function() {
var rowCol = $(this);
rowCol.find('td:eq(4)').each(function() {
var mytd = $(this);
var rowValue = parseFloat($(this).text());
console.log(rowValue === 0)
if (rowValue > 1) {
mytd.addClass('def').removeClass('defects');
} else {
mytd.addClass('defects').removeClass('def');
}
});
});
.defects {
background: #e74c3c;
color: #fff;
padding: 3px;
border-radius: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>0</td>
<td>6</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>
You can run the demo above and see the result.

Select option comparing with Table Row

I have this button to append a <Select> but the option should not be showing what is already in the table row (Math, English, Science) So I needed to only Show the PE SUBJECT in the <select> options, I tried doing the .each in JQuery but I cant compare the two. I'm trying to make my table dynamic.
This is my sample JSFiddle https://jsfiddle.net/ta73h4ez/16/
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<script>
$( document ).ready(function() {
$( "#add" ).click(function() {
$('tbody').append('<tr><td><select><option value="math">Math</option><option value="English">English</option><option value="Science">Science</option><option value="PE">PE</option></select></td><tr>');
});
});
</script>
<h2>HTML Table</h2>
<table>
<tbody>
<tr>
<th>Subject</th>
<th>Start Time</th>
<th>End Time</th>
</tr>
<tr>
<td>Math</td>
<td>8am</td>
<td>9am</td>
</tr>
<tr>
<td>English</td>
<td>10am</td>
<td>1pm</td>
</tr>
<tr>
<td>Science</td>
<td>1pm</td>
<td>3pm</td>
</tr>
</tbody>
</table>
<input type="button" value = "Add Subject" id ="add">
</body>
</html>
you can compare like :
$('table').find('tr').each(function(){
var td1=$(this).find('td').eq(0).text();
$('select').find('option').each(function(){
var op = $(this).text();
if(op==td1)
{
$(this).hide();
}
});
});
This is my sample JSFiddle
jsFiddle
Change your javascript function to below. You can optimize this code according to your requirements.
$( document ).ready(function() {
$( "#add" ).click(function() {
var options = getOptions();
var optionsString = "";
for(var i = 0; i< options.length; i++){
optionsString += '<option value="'+options[i]+'">'+options[i]+'</option>';
}
$('tbody').append('<tr><td><select>'+optionsString +'</select></td><tr>');
});
var getOptions = function(){
var options = ["Math", "English", "Science", "PE"];
var allRows = $('table').find('tr');
for(var i=0; i< allRows.length && options.length>0; i++){
var subjectText = $(allRows[i]).find('td').eq(0).text();
var index = options.indexOf(subjectText);
options = options.splice(index, 1);
}
return options;
};
});

Using not(selector) on dynamically create element

The code basically edit a table cell.
I want to use the not() method so that everytime I click outside the temporary input created I replace it with a table cell. I guess the code run in a block and doesn't detect any input with an id of "replace" so how can I fix that ?
Also I want to store the element (th or td) that fire the first event(dblclick) so that I can use it to replace the input with the right type of cell but it seems to only stores the element that first triggers the event and I don't really understand why.
Full code here
$(function () {
$(document).on("dblclick", "th, td", function (event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
var $typeCell = $(event.currentTarget); // Store element which trigger the event
$("body").not("#replace").on("click", function () { // .not() method
cellText = $("#replace").val();
if ($typeCell.is("th")) {
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
}
else {
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
});
});
I have modified HTML and JavaScript to avoid any possible errors. The correct practice is to wrap all th's in a thead and all td's in tbody.
$(document).on("dblclick", "th, td", function(event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
});
$("body").on("click", function() {
if (event.target.id != 'replace' && $('#replace').length != 0) {
var cellText = $("#replace").val();
if ($('#replace').parents().is('thead'))
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
else
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
table {
border-collapse: collapse;
margin: 20px;
min-width: 100px;
}
table,
th,
td {
border: 1px solid grey;
padding: 4px;
}
th {
background: springgreen;
}
tr:nth-child(odd) {
background: rgba(0, 255, 127, 0.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table>
<thead>
<tr>
<th scope="col">Uno</th>
<th scope="col">Dos</th>
<th scope="col">Tres</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data1</td>
<td>Data2</td>
<td>Data3</td>
</tr>
<tr>
<td>Data4</td>
<td>Data5</td>
<td>Data6</td>
</tr>
</tbody>
</table>
</div>

JavaScript - Traversing the HTML DOM using childNodes causes errors in Non IE browsers

I have the following table being rendered in my browser. It's generated from the server side.
<table id="tblQuestions" class="tblQuestionsContainer" border="0">
<tr>
<td id="1" class="tdQuestion">Are u an indian citizen ?</td>
</tr><tr>
<td><table id="answer-1" border="0">
<tr>
<td><input id="answer-1_0" type="radio" name="answer-1" value="1" /><label for="answer-1_0">Yes</label></td><td><input id="answer-1_1" type="radio" name="answer-1" value="0" /><label for="answer-1_1">No</label></td>
</tr>
</table></td>
</tr><tr>
<td id="2" class="tdQuestion">Do you have a passport ?</td>
</tr><tr>
<td><table id="answer-2" border="0">
<tr>
<td><input id="answer-2_0" type="radio" name="answer-2" value="1" /><label for="answer-2_0">Yes</label></td><td><input id="answer-2_1" type="radio" name="answer-2" value="0" /><label for="answer-2_1">No</label></td>
</tr>
</table></td>
</tr>
</table>
Now I am using the following code in my JavaScript to validate the radio button's checked state.
var tblQuestionBoard=document.getElementById("tblQuestions");
tblAnswer = tblQuestionBoard.rows[1].childNodes[0].childNodes[0]
Now tblAnswer should be an object having the Table with id "answer-1"
In IE, I am getting it. But in Mozilla and rest of the browsers I am getting it as undefined.
How to solve this?
It's because you're using childNodes and whitespaces in the DOM are considered to be text nodes by Firefox et. al but not IE
See this answer for an explanation
My suggestions
1.Set up some wrapper functions that ignore any nodeType other than 1 (ELEMENT_NODE) to do DOM traversing. Something like
function child(elem, index) {
// if index is not supplied, default is 1
// you might be more comfortable making this 0-based
// in which case change i initial assignment value to 0 too
index = index || 1;
// get first child element node of elem
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
// use the index to move to nth-child element node
for(var i=1; i < index;i++) {
(function() {
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
and use like so - Working Demo - (Code at the bottom of the answer for reference)
<table id="myTable">
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>
<script type="text/javascript">
child(document.getElementById('myTable'), 2); // will get the tbody
</script>
2.Use getElementbyId(), getElementsByTagName() or getElementsByName() instead of relying on position in the DOM
3.Use a JavaScript library that abstracts away browser differences (jQuery comes highly recommended)
The Demo Code
<!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" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('getCellContents').onclick = getCellContents;
}
function child(elem, index) {
index = index || 1;
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
for(var i=1; i < index;i++) {
(function() {
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
function getCellContents() {
var row = parseInt(document.getElementById('row').value, 10);
var column = parseInt(document.getElementById('column').value, 10);
var result;
var color;
var table = document.getElementById('table');
var cells = table.getElementsByTagName('td');
for (var i= 0; i < cells.length; i++) {
(function() {
cells[i].bgColor = '#ffffff';
})();
}
if (row && column) {
var tbody = child(table , 2);
var selectedRow = (row <= tbody.getElementsByTagName("tr").length)? child(tbody, row): null;
var selectedCell = (selectedRow && column <= selectedRow.getElementsByTagName("td").length)? child(selectedRow, column): null;
if (selectedRow && selectedCell) {
selectedCell.bgColor = '#00ff00';
result = selectedCell.innerHTML;
color = '#b7b7b7';
}
else {
result = 'Cell does not exist';
color = '#ff0000';
}
}
else {
result = 'You must provide numeric arguments for Row and Column Number';
color = '#ff0000';
}
var results = document.getElementById('results');
results.innerHTML = result;
results.style.color = color;
}
</script>
<title>DOM Traversal</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
font-family: Verdana, Helvetica, Arial;
font-size: 0.8em;
}
h2 {
text-align:center;
}
table {
border: 1px solid #000;
border-collapse: collapse;
}
th, td {
border: 1px solid #000;
padding: 2px;
}
fieldset {
border: 0;
}
label {
display: block;
width: 120px;
text-align: right;
float: left;
padding-right: 10px;
margin: 5px 0;
}
input {
margin: 5px 0;
}
input.text {
padding: 0 0 0 3px;
width: 172px;
}
input.button {
margin: 15px 0 0 130px;
}
span {
font-weight: bold;
color: #b7b7b7;
}
</style>
</head>
<body>
<h2>Example to demonstrate use of JavaScript DOM traversing wrapper functions</h2>
<div style="margin: 0 auto; width: 600px;">
<fieldset>
<label for="row">Row Number:</label><input id="row" class="text" type="text" /><br/>
<label for="column">Column Number:</label><input id="column" class="text" type="text" /><br/>
<input id="getCellContents" type="button" class="button" value="Get Cell Contents" />
</fieldset>
<p>Results: <span id="results"></span></p>
<table id="table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Banana</td>
<td>Apple</td>
<td>Orange</td>
<td>Pineapple</td>
<td>Cranberry</td>
</tr>
<tr>
<td>Monkey</td>
<td>Giraffe</td>
<td>Elephant</td>
<td>Tiger</td>
<td>Snake</td>
</tr>
<tr>
<td>C#</td>
<td>Java</td>
<td>Python</td>
<td>Ruby</td>
<td>Haskell</td>
</tr>
<tr>
<td>France</td>
<td>Spain</td>
<td>Italy</td>
<td>Germany</td>
<td>Netherlands</td>
</tr>
</tbody>
</table>
<p style="font-weight:bold;">The Code:
<pre><code>
<script type="text/javascript">
window.onload = function() {
document.getElementById('getCellContents').onclick = getCellContents;
}
function child(elem, index) {
index = index || 1;
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
for(var i=1; i < index;i++) {
(function() {
if(elem)
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
function getCellContents() {
var row = parseInt(document.getElementById('row').value, 10);
var column = parseInt(document.getElementById('column').value, 10);
var result;
var color;
var table = document.getElementById('table');
var cells = table.getElementsByTagName('td');
for (var i= 0; i < cells.length; i++) {
(function() {
cells[i].bgColor = '#ffffff';
})();
}
if (row && column) {
var tbody = child(table , 2);
var selectedRow = (row <= tbody.getElementsByTagName("tr").length)?
child(tbody, row): null;
var selectedCell = (selectedRow && column <= selectedRow.getElementsByTagName("td").length)?
child(selectedRow, column): null;
if (selectedRow && selectedCell) {
selectedCell.bgColor = '#00ff00';
result = selectedCell.innerHTML;
color = '#b7b7b7';
}
else {
result = 'Cell does not exist';
color = '#ff0000';
}
}
else {
result = 'You must provide numeric arguments for Row and Column Number';
color = '#ff0000';
}
var results = document.getElementById('results');
results.innerHTML = result;
results.style.color = color;
}
</script>
</code>
</pre>
</p>
</div>
</body>
</html>

Categories