Page 1 of 1

Make a multiplication table with and without jQuery variable size, shows benefits of using a library and regular DOM techn Rate Topic: -----

#1 crazyjugglerdrummer  Icon User is offline

  • GAME OVER. NERD WINS.
  • member icon

Reputation: 119
  • View blog
  • Posts: 690
  • Joined: 07-January 09

Posted 07 April 2009 - 05:45 AM

Salutations all, this is CrazyJugglerDrummer with a tutorial on how to make a multiplication table in javascript.

We could, of course, just type out all the <tr> and <td> elements in a table in the actual html like this:
<table>
	<tbody>
		<tr>
			<td>1</td>
			<td>2</td>
			<td>3</td>
		</tr>
		<tr>
			<td>2</td>
			<td>4</td>
			<td>6</td>
		</tr>
		<tr>
			<td>3</td>
			<td>6</td>
			<td>9</td>
		</tr>
	</tbody>
</table>



which works perfectly fine, but we would have to have all the values in before-hand, and we couldn’t change the table’s size based on user input. Javascript makes this a lot easier (trust me :) ).

So we begin with a very simple HTML document that we will modify with javascript.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
//our javascript stuff
</head>

<body>

	<table>
		<tbody id="myTable">
		</tbody>
	</table>

</body>

</html>



That is all we will have in the body as we will be adding our content to the table via javascript. The rest of our work is in the head.

The first time around we shall use jQuery to our advantage (because it makes everything much easier). First things first, we include the jQuery library and make sure that the page has loaded the html before executing the script. Since we are modifying the table, we can’t do that until the table has been loaded first.
<head>
<script src="jquery.js"></script> //or where-ever you have your jQuery library
<script>
$(document).ready(function() {

//do stuff when the document’s ready

});
</script>
</head>




Now comes the fun part. We need to select the table and add the appropriate number of rows. We can just use jQuery’s append function to continue adding children elements to our table element.
$(document).ready(function() {

var max=prompt("How many rows of multiplication would you like?"); //get input
var table= $("#multiplicationTable");						 //select table by id
var row2add=””;				//make variable for row to be inserted in table

for (var x=1; x<=max; x++) //start loop at 1 because we don’t need a row of all 0’s
{
	row2add="<tr>";
	
	//add data to row

	row2add += "</tr>";
	
	table.append(row2add);  //add the row to the table
}



To put the data into the row we just keep concatenating data onto the string.
for (var x=1; x<=max; x++)
{
	row2add="<tr>";
	
	for (var y=1; y<=max; y++)
	{
		row2add += "<td>" + x*y + "</td>"; 
	}
	row2add += "</tr>";
	
	table.append(row2add);
}



We put the data in the row BEFORE we add the row to the HTML because once we add the row it’s kind of hard to select it (unless we try to give each generated row a unique id attribute and then select it somehow, but this way’s much simpler).

This should now produce a nice little multiplication table when you preview it in a browser. But we can spice it up a bit with some color via CSS and jQuery. jQuery makes it incredibly easy to add a class of even to all the even rows and data of the table with filters.
$("tr:even").addClass("even");
$("tr:odd").addClass("odd");
$("td:even").addClass("even");
$("td:odd").addClass("odd");



This creates an alternating even-odd pattern for the rows and columns. This will now allow us to make a CSS rule that makes alternating colors. We also add some size control to the table cells, to make the numbers look more nicely aligned and not cramped.
<style type="text/css">
td { margin: 3px; 
width: 2em;
padding-left: 4px;
}

tr.even td.even { background-color: #ee22bb; }

tr.even td.odd { background-color: #00ffbb; }

tr.odd td.even { background-color: #ee44cc; }

tr.odd td.odd { background-color: #7799dd; }

</style>



We have one alternating pattern for all of the even rows of the table, and a different pattern for all of the odd rows of the table, via some child selectors. Preview the file again in a browser. It should look a lot nicer, and have pretty colors! (To see all of the code together, view the full code at the end of the tutorial.)


So that was a lot of fun and fast with jQuery. So now to realize how much it really did for us, we’ll do the same using plain old javascript and DOM techniques to achieve the same result.

We have the same HTML and CSS stuff, we just need to go about our javascript differently. Our two tasks that we accomplished with javascript were adding rows and data to the table, and then adding the classes to those rows and data. We could try and do both in one fell swoop when adding the rows to the table:
row2add += “<tr class=\”even\”>”;


and then alternate between even and odd rows (AND datas). We also have to make sure we escape the “ marks properly, and hope things don’t get misinterpreted by the browser. This gets pretty messy pretty quickly, so we’re going to do the two separately. (make the table, then apply the classes)


The first problem is that we can’t just use append to add each row of the table to the HTML. We had to put our data into the row before we added the row previously, because once we added the rows we couldn’t easily select them to add content to each one. We will have to make the entire table’s HTML as a string, then add the string to the element with innerHTML.

Things start off rather similarly:
var max=prompt("How many rows of multiplication would you like?");

var table= document.getElementById("myTable"); //use DOM way instead of jQuery way

var row2add="",finalTable="";

for (var x=1; x< max; x++)
{
	row2add="<tr>";
	
	for (var y=1; y<=max; y++)
	{
		row2add += "<td>" + x*y + "</td>"; 
	}
	row2add += "</tr>";
	finalTable += row2add;  //add the finished row to the final product
}

table.innerHTML = finalTable;
[code]

We make each row, stick them into finalTable, then add them to the page. That wasn’t so bad, now we just have to add the classes to the appropriate rows and data elements. 


We begin by selecting all of the children of the <tbody> element (the one that we added all of the stuff to previously). This effectively gets us all of the rows, which we loop through, adding the right class to each one.
[code]
var rows=table.childNodes;  //get all rows

for (var z=0; z<rows.length; z++)
{
	if (z%2 ==0)	   //alternate between each one
		rows[z].setAttribute("class","even");
	else
		rows[z].setAttribute("class","odd");
}



Now we have to take each of those rows, and do the same thing to it. So we add another variable and a nested loop.
var rows=table.childNodes;
var data;							  

for (var z=0; z<rows.length; z++)
{
	if (z%2 ==0)
		rows[z].setAttribute("class","even");
	else
		rows[z].setAttribute("class","odd");
		
	data=rows[z].childNodes;	 //get all of the children of that row ( <td>’s )
		
	for (var q=0; q<max; q++)
	{
		if (q%2 ==0)
			data[q].setAttribute("class","even");
		else
			data[q].setAttribute("class","odd");
	 }
}



Now we have everything in place, we need to make it run after the page loads. With jQuery, we just used document.ready() to do this, but now we will have to make a function and assign an event for when the page loads. So we wrap all of the in a function, and assign it to an event.
<script type="text/javascript">
function start() {					   
// everything the same
} 

window.onload= start; //assign reference to function
</script>


If you’re unsure about this, see the full code at the end of the tutorial.


So there you have it, multiplication tables with and without jQuery! Thanks for reading! :)

Happy Coding!!




Full code from tutorial:

With jQuery (a lot easier with the help of a library)
<!DOCTYPE htmlPUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<script src="jquery.js"></script>
<script>

$(document).ready(function() {

var max=prompt("How many rows of multiplication would you like?");

var table= $("#multiplicationTable");
var row2add="";

for (var x=1; x<=max; x++)
{
	row2add="<tr>";
	
	for (var y=1; y<=max; y++)
	{
		row2add += "<td>" + x*y + "</td>"; 
	}
	row2add += "</tr>";
	
	table.append(row2add);
}

$("tr:even").addClass("even");
$("tr:odd").addClass("odd");
$("td:even").addClass("even");
$("td:odd").addClass("odd");

});
</script>
<style type="text/css">
td { margin: 3px; 
width: 2em;
padding-left: 4px;
}

tr.even td.even { background-color: #ee22bb;
}

tr.even td.odd { background-color: #00ffbb;
}

tr.odd td.even { background-color: #ee44cc;
}

tr.odd td.odd { background-color: #7799dd;
}

</style>
</head>

<body>

	<table id="multiplicationTable">
	</table>

</body>

</html>



Without jQuery (it’s good to know how to do things without jQuery, so you don’t completely rely on it for everything. You can understand how the library works, and still function in situations where you can’t use it. Knowing this makes you a more competent programmer and extends your knowledge of the language.)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>

<script type="text/javascript">
function start() {


var max=prompt("How many rows of multiplication would you like?");

var table= document.getElementById("myTable");

var row2add="",finalTable="";

for (var x=1; x< max; x++)
{
	row2add="<tr>";
	
	for (var y=1; y<=max; y++)
	{
		row2add += "<td>" + x*y + "</td>"; 
	}
	row2add += "</tr>";
	finalTable += row2add;
}

table.innerHTML = finalTable;


var rows=table.childNodes;
var data;

for (var z=0; z<rows.length; z++)
{
	if (z%2 ==0)
		rows[z].setAttribute("class","even");
	else
		rows[z].setAttribute("class","odd");
		
	data=rows[z].childNodes;
		
	for (var q=0; q<max; q++)
	{
		if (q%2 ==0)
			data[q].setAttribute("class","even");
		else
			data[q].setAttribute("class","odd");
	}
}

} //end function start

window.onload= start;
</script>
<style type="text/css">
td { margin: 3px; 
width: 3em;
padding-left: 4px;
}

tr.even td.even { background-color: #ee22bb;
}

tr.even td.odd { background-color: #00ffbb;
}

tr.odd td.even { background-color: #ee44cc;
}

tr.odd td.odd { background-color: #7799dd;
}

</style>
</head>

<body>

	<table>
		<tbody id="myTable">
		</tbody>
	</table>

</body>

</html>


This post has been edited by crazyjugglerdrummer: 07 April 2009 - 11:01 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Make a multiplication table with and without jQuery

#2 crazyjugglerdrummer  Icon User is offline

  • GAME OVER. NERD WINS.
  • member icon

Reputation: 119
  • View blog
  • Posts: 690
  • Joined: 07-January 09

Posted 14 May 2009 - 06:02 PM

One could have used the DOM traversing methods in level 0 etc. to perform the without jQuery part, but using only innerHTML can be more backward compatible (although its not terrible important and other features used in the code may scratch the backward compatibility :D )

my typo: make sure you always use <script type="text/javascript"> </script> , specifying the MIME type of text/javascript to make sure browsers know how to interpret the contents.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1