On Jun 14, 7:32 am, Cgnost <[EMAIL PROTECTED]> wrote:
> I've created a custom tooltip function to be used on a website. I'm
> trying to code it in such a way that by giving any img tag an
> attribute with tooltip="productid" it will attach the correct
> onmouseover and onmouseout event.
>
> Here is the code:
>
> loadEvents: function() {
>                 var images = document.getElementsByTagName("img");

It seems David has already given you a solution you are happy with,
however it's worth pointing out that the document already has an
images collection ready for you to use:

  var images = document.images;

It's a live collection, so as you add/remove images, they are
automatically added/removed from the collection.

Also, the number of lines of code is not any indicator of efficiency
or speed.  You will often find that looping over a collection is much
quicker than using $$, and faster again than .each.  If performance is
an issue (and maybe it isn't for you) consider the above.

>                 var myElement = null;

There is rarely any point in initialising a variable as null, if you
use:

   var myElement;

it is assigned a value of undefined, which is suitable in nearly all
cases.

>                 var myProductID = 0;

Same here.  You are going so assign a value of the tool tip, so there
doesn't seem much point in assigning a value of zero.


>                 for (var i = 0; i < images.length; i++) {
>                         myElement = images[i];
>                         if (myElement.hasAttribute("tooltip")) {
>                                 myProductID = 
> myElement.getAttribute("tooltip");
>                                 Event.observe(myElement, 'mouseover', 
> function()
> { productTooltip.show(myProductID,myElement); });

Here is where your issue comes from - both myProductID and myElement
form closures back to their respective variables that are associated
with the function's execution object.  Their value in all cases will
be whatever value was last assigned them before the function finished
so all your handlers will have references to the same value.

There are alternatives to that proposed by David - but if it suits,
use it.


--
Rob


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Spinoffs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-spinoffs?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to