473,378 Members | 1,360 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Efficiently detecting a click in a large table

For an abstract algebra class that I will be teaching,
I'm trying to convert a text-based game that I wrote
in Common Lisp to a graphical game in javascript. (I
know nothing of javascript, but I have three books
from the library that I have been s*l*o*w*l*y going
through.)

Currently I have a large, say, 30x20, table

<table id="GameTable" >
<tr<td>A</td<td>B</td<td>C</td... </tr>
<tr<td>D</td<td>E</td<td>F</td... </tr>
...
</table>

I'm accessing elements via

var game_table = document.getElementById('GameTable');
var curr_cell;

function game_node(x,y) {
curr_cell = game_table.rows[x].cells[y];
return(curr_cell.firstChild);
};

and I'm able to write/read to

game_node(x,y).nodeValue

just fine. But here's where I'm stuck:

I'd like, when the user clicks on, say, cell (3,5),
that a function-call

UpdateGame(3,5)

is invoked. Is there a way I can do this NEITHER
having an "onclick=" NOR an "id=" for each and every
<td>? I seek something like having a single "id=" and
"onclick=" for the entire table, e.g,

<table id="GameTable"
onclick="UpdateGame(this.rowIndex, this.colIndex)">

where -somehow- variables rowIndex and colIndex were
automagically set by the mouse-click.

Ta, Jonathan King Math dept, Univ. of Florida
Jun 27 '08 #1
8 2242
You can use event.target/event.srcElement to determine the clicked
node and check if it is inside the table. Then you can use cellIndex
and rowIndex properties of the cell and row to get the coordinates.

Simple sample (function to handle the click must be set after the
element id="GameTable" is loaded):
document.getElementById("GameTable").onclick = function(e) {
e = e || window.event;

for (var td = e.target || e.srcElement; td && td != this; td =
td.parentNode)
if (td.tagName == "TD" && td.parentNode.parentNode.parentNode ==
this) {
UpdateGame(td.parentNode.rowIndex, td.cellIndex);
break;
}
}
Jun 27 '08 #2
On May 18, 11:37 pm, "P. Prikryl" <p.prik...@gmail.comwrote:
You can use event.target/event.srcElement to determine the clicked
node and check if it is inside the table. Then you can use cellIndex
and rowIndex properties of the cell and row to get the coordinates.
For Google food, this has been termed "event delegation" meaning a
parent element is watching for events that bubble up from child
elements.

http://yuiblog.com/blog/2007/01/17/event-plan/
http://developer.yahoo.com/yui/examp...elegation.html

Peter
Jun 27 '08 #3
Peter Michaux wrote:
On May 18, 11:37 pm, "P. Prikryl" <p.prik...@gmail.comwrote:
>You can use event.target/event.srcElement to determine the clicked
node and check if it is inside the table. Then you can use cellIndex
and rowIndex properties of the cell and row to get the coordinates.

For Google food, this has been termed "event delegation" meaning a
parent element is watching for events that bubble up from child
elements.

http://yuiblog.com/blog/2007/01/17/event-plan/
http://developer.yahoo.com/yui/examp...elegation.html
However, the technically correct no-buzzword term is "Event bubbling"
(mentioned here before) or, more generally, "Event dispatch":

http://www.w3.org/TR/DOM-Level-2-Eve...ml#Events-flow
http://www.w3.org/TR/2007/WD-DOM-Lev...vents-20071221
PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Jun 27 '08 #4
On May 19, 2:37 am, "P. Prikryl" <p.prik...@gmail.comwrote:
You can use event.target/event.srcElement to determine ...
Thank you (dziekuje bardzo) P. Prikryl, Peter and Thomas.

The code works for me in FF under MacOSX, and there are a
few places where I don't know how/why it works. Currently,
inside <BODY></BODYI have

<table id="GameTable">
<tr<td>AA</td<td>BB</td<td>CC</td</tr>
<tr<td>DD</td<td>EE</td<td>FF</td</tr>
</table>

<script language="JavaScript">
function UpdateGame(x,y) {alert("USER clicked (" + x + "," + y +
").")};

document.getElementById("GameTable").onclick = function(e) {
e = e || window.event;
for (var tdvar = e.target || e.srcElement;
tdvar && tdvar != this;
tdvar = tdvar.parentNode)
if (tdvar.tagName == "TD" &&
tdvar.parentNode.parentNode.parentNode == this) {
UpdateGame(tdvar.parentNode.rowIndex, tdvar.cellIndex);
break;
}
};
</script>

Q1: Why is "TD" capitalized? I understand that HTML is
case-insensitive whereas JS is sensitive. The ==
comparison is done at the JS level; how did you know to use
uppercase?

Q2: Why 3 levels of parentNode, rather than 2, in

tdvar.parentNode.parentNode.parentNode == this

? Is it that `tdvar' is bound to an event whose parent is
<TD>? Or is it that `tdvar' is bound to <TD>, but that an
implicit <TBODYis being inserted into my innocent
<table>? --I am inferring the latter from this page:

http://htmlhelp.com/reference/html40/tables/tbody.html

I haven't looked at HTML for a l*o*n*g time, I don't
remember there even being a <TBODYtag when I was
designing the few tables I use on my site.

Ta, Jonathan King Math dept, Univ. of Florida
Jun 27 '08 #5
sq*******@math.ufl.edu escribió:
Q1: Why is "TD" capitalized? I understand that HTML is
case-insensitive whereas JS is sensitive. The ==
comparison is done at the JS level; how did you know to use
uppercase?
You've said it all, that's how JavaScript works:
>>"a"=="A"
false
>>"A"=="A"
true

Q2: Why 3 levels of parentNode, rather than 2, in

tdvar.parentNode.parentNode.parentNode == this
Again, you got the key yourself: TBODY.

In general, you have an HTML source code that is parsed by the browser
and converted into a DOM tree. What you can manipulate with JavaScript
is the resulting node tree. This becomes more evident if you have
invalid markup like "<div>Foo</p>".

I suggest you install the Firebug extension for Firefox and have a look
at the DOM tree. Once you get used to Firebug you can't code without it.
--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://bits.demogracia.com
-- Mi web de humor al baño María: http://www.demogracia.com
--
Jun 27 '08 #6
On May 19, 6:23 am, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
Peter Michaux wrote:
On May 18, 11:37 pm, "P. Prikryl" <p.prik...@gmail.comwrote:
You can use event.target/event.srcElement to determine the clicked
node and check if it is inside the table. Then you can use cellIndex
and rowIndex properties of the cell and row to get the coordinates.
For Google food, this has been termed "event delegation" meaning a
parent element is watching for events that bubble up from child
elements.
http://yuiblog.com/blog/2007/01/17/event-plan/
http://developer.yahoo.com/yui/examp...elegation.html

However, the technically correct no-buzzword term is "Event bubbling"
(mentioned here before) or, more generally, "Event dispatch":

http://www.w3.org/TR/DOM-Level-2-Eve...vents-20071221
"Event bubbling" is the mechanics of the chain of responsibility
pattern implemented in the DOM. It is just the fact that an event
does bubble.

"Event delegation" is an application-level concept of how a bubbling
event is used. If a ancestor node is handling an event on behalf of a
node that would normally handle the event itself then that is event
delegation. Event bubbling is what makes event delegation possible.

Peter
Jun 27 '08 #7
Peter Michaux wrote:
On May 19, 6:23 am, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
>Peter Michaux wrote:
>>On May 18, 11:37 pm, "P. Prikryl" <p.prik...@gmail.comwrote:
You can use event.target/event.srcElement to determine the clicked
node and check if it is inside the table. Then you can use cellIndex
and rowIndex properties of the cell and row to get the coordinates.
For Google food, this has been termed "event delegation" meaning a
parent element is watching for events that bubble up from child
elements.
http://yuiblog.com/blog/2007/01/17/event-plan/
http://developer.yahoo.com/yui/examp...elegation.html
However, the technically correct no-buzzword term is "Event bubbling"
(mentioned here before) or, more generally, "Event dispatch":

http://www.w3.org/TR/DOM-Level-2-Eve...vents-20071221

"Event bubbling" is the mechanics of the chain of responsibility
pattern implemented in the DOM. It is just the fact that an event
does bubble.

"Event delegation" is an application-level concept of how a bubbling
event is used. If a ancestor node is handling an event on behalf of a
node that would normally handle the event itself then that is event
delegation. Event bubbling is what makes event delegation possible.
Read again.
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
Jun 27 '08 #8
On May 19, 12:35 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
....
Must be at least

<script type="text/javascript">

The `language' attribute is deprecated, the `type' attribute is required:
Ah; ta,
Q1: Why is "TD" capitalized? ...

See <http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-822762427>.

However, as XHTML may also be served as text/html in which case it may
be parsed as HTML, I consider case-insensitive matching to be less
error-prone:

if (tdvar.tagName.toLowerCase() == "td" ...)
Good; I'm going to make this my std practice.

I haven't yet processed your more technical comments; I'm still
reading
the textbooks. Thanks again.

Jonathan King Math dept, Univ. of Florida
Jun 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Raptor | last post by:
I'm using a single script to generate a table with <input>s in each row. I fill the array with initial values, then write it out to the table and let the user edit the values. Something like: ...
7
by: Adam Hartshorne | last post by:
As a result of a graphics based algorihtms, I have a list of indices to a set of nodes. I want to efficiently identify any node indices that are stored multiple times in the array and the...
1
by: beachnut | last post by:
Hi, all. This should be pretty easy: When parsing my XmlDocument object with a validating reader, what's the proper way to detect when it "exits" an element's block? It's the first time I've...
15
by: AndrewD | last post by:
Hi, Using scanf, is it possible to detect input numbers where the decimal count is too large? eg. scanf("%19lg",&var);
2
by: Sam-Kiwi | last post by:
I've spent the last 6 months developing a pay-per-download website using ASP.NET Users purchase documents and then download them. The intention is that users are only charged for documents...
7
by: jab3 | last post by:
Hello. I'm wondering if someone can answer something I'm sure has been answered a thousand times before. I am apparently just too dumb to find the answer. :) I've found information about the...
2
by: petermichaux | last post by:
Hi, I don't know if there is a way to feature detect for this or not. I have a list and the user can click on items to select. I would like that they can command-click on Mac or control-click on...
7
by: Ming | last post by:
For example, 100,000 records, each record has 10 fields and may belong to one or more categories. How shall I save those records in DB? I think it is a very typical concern for most online shopping...
15
by: RobG | last post by:
When using createEvent, an eventType parameter must be provided as an argument. This can be one of those specified in DOM 2 or 3 Events, or it might be a proprietary eventType. My problem is...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.