N6+ event bubble?

J

Jesse Wade

Hello all. In N6+ is it possible to have a whole bunch of TD cells
in a table and have a click event handler on the TABLE object that identifies
the clicked cell?

I don't want to have individual click handlers on each TD as the page
will become too large.

So the concept would be something like:

<SCRIPT language="javascript">
function OnClick(E){
alert( some code that identifies the value of the clicked cell );
}
</SCRIPT>

<TABLE onclick="Onclick();">
<TR><TD>1</TD><TD>2</TD><TD>3</TD><TD>4</TD><TD>5</TD></TR>
<TR><TD>6</TD><TD>7</TD><TD>8</TD><TD>9</TD><TD>10</TD></TR>
<TR><TD>11</TD><TD>12</TD><TD>13</TD><TD>14</TD><TD>15</TD></TR>
<TR><TD>16</TD><TD>17</TD><TD>18</TD><TD>19</TD><TD>20</TD></TR>
<TR><TD>21</TD><TD>22</TD><TD>23</TD><TD>24</TD><TD>25</TD></TR>
<TR><TD>26</TD><TD>27</TD><TD>28</TD><TD>29</TD><TD>30</TD></TR>
<TR><TD>31</TD><TD>32</TD><TD>33</TD><TD>34</TD><TD>35</TD></TR> etc...
</TABLE>
 
Y

Yann-Erwan Perio

Jesse said:
Hello all. In N6+ is it possible to have a whole bunch of TD cells
in a table and have a click event handler on the TABLE object that identifies
the clicked cell?

Yes, and this is actually the approach I prefer, since it permits to
control the entry point in the code (conditional init) and facilitates
the maintenance.
<TABLE onclick="Onclick();">

This was your biggest problem; the construct you've used is similar to:

myTable.onclick = function(event) {
Onclick();
}

The onclick attribute value is in fact wrapped into an anonymous
function, which holds the event object, named "event"; you need to pass
this event object to your inner handler, in order to be able to
determine the original target.

Once you have the event, you'll have to pay attention to its target:
- it can be a text node, in which case you have to go up until
you find the TD,
- it can be a TD,
- it could be an intermediate element (like TR, TBODY) or the table
itself (if clicked on a border, for instance).


---
<script type="text/javascript">
var buf=[];
for(var ii=0; ii<10; ii++){
buf.push("<tr>");
for(var k=1; k<=10; k++){
buf.push("<td id='td"+(k+ii*10)+"'>"+(k+ii*10)+"<\/td>");
}
buf.push("<\/tr>");
}
document.write(
"<table id='MyTable' onclick='foo(event, this)'>"+
buf.join("") +
"<\/table>"
);

function foo(evt, table){
var el;
evt=evt||window.event;
el=evt.target||evt.srcElement;

for(;el&&el!=table;el=el.parentNode)
if(el.nodeName.toLowerCase()=="td")
break;

alert(el.id); //either the td or an intermediate element
}
</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top