views:

2016

answers:

1

Hi,

I got the following situation:

I got a table structure like this:

<tr>
  <td>text</td>
  <td>text</td>
  <td>text</td>
  <td><a href="#"><img src="#" /></td>
  <td><span style="display:hidden"><a href="#">e</a> <a href="#">e</a></td>
</tr>

What I'm doing with the following function is displaying the hidden span on hover of the table row. However it quirks whenever I hover the childElements inside the tr: the anchored image and the span itself. How can I fix this?

// Reveal item options on hover
$$('#financedata tr').invoke('observe', 'mouseover', function(event) {
 event.target.up().childElements()[4].childElements()[0].toggle();     
}); 
$$('#financedata tr').invoke('observe', 'mouseout', function(event) {
 event.target.up().childElements()[4].childElements()[0].toggle();
});
+3  A: 

Try the following:

$$('#financedata tr').invoke('observe', 'mouseout', function(event) {
    this.up('tbody').childElements()[4].childElements()[0].toggle();
});

The key is using "this". With Prototype, "this" will always be the element the event is bound to, whereas event.target (which you shouldn't use as it is not cross-browser) and event.findElement() will be the actual element that the event occurred on. The .up('tbody') is merely a personal preference, and ensures that you are selecting the parent tbody, and nothing else. Try it with or without.

Read: http://www.prototypejs.org/api/event/observe for more information and examples on how Event bubbling works.

hobodave
P.S. You may need to change tbody to table depending on your DOM markup.
hobodave
Also note that some browsers (Firefox) implicitly add a tbody to your DOM when you don't specify one, so watch out for this.
hobodave
Thanks a lot! It works :) I will be reading more about Event bubbling and the use if this in an observer. I actually did not had to use up() with this since as you stated, the event is bound to the <tr>.
richard
Btw I found thead and tbody to be quite buggy in Firefox. Do you happen to know a solution to my other problem with Firefox? http://stackoverflow.com/questions/1111337/prototype-element-update-multiple-objects
richard
richard: I answered it.
hobodave