views:

129

answers:

1

Hi

Event.observe(window,"load",function() {
  $$(".elem_classs").findAll(function(node){
    return node.getAttribute('title');
  }).each(function(node){
    new Tooltip(node,node.title);
    node.removeAttribute("title");
  });
});

Using above method, I can retrieve all elements having ".elem_class" and apply some javascript functions on them. But I have a modal/popup box which has some elements also having ".elem_class" and these dont get in the scope of findAll/each as they are loaded into the dom thru ajax.

How do I apply the same to dynamically loaded elements as well? I am using Prototype Library. (I have used JQuery's Live function which keeps track of all future elements, but need to achieve something similar using Prototype)

Thanks.

A: 

As far as I know, event delegation is bot built into Prototype, but it shouldn't be too difficult to do on your own. Simply add a handler to observe the event on the body then use Event#findElement to check if it matches your selector.

Here is a sample function that sets up the delegation for you (run this on load):

/**
 * event_type: 'click', 'keydown', etc.
 * selector: the selector to check against
 * handler: a function that takes the element and the event as a parameter
 */
function event_delegator(event_type, selector, handler) {
  Event.observe(document.body, event_type, function(event) {
    var elt = Event.findElement(event, selector);
    if (elt != document)
      handler(event, elt);
  });
}

You could probably extend Element to handle this for you, streamlining everything. Hope this helps!

Edit: The hover event (or mousein/mouseout) should be a good event for a tooltip. Also, don't get all the elements on load, that's unnecessary when using event delegation. Here's a link to more about event delegation: http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/

geowa4
hmm.. in the example in my question, on document load I get all required elements and apply tooltip to them. My problem is that this "tootip" doesn't get applied to the elements in the modal window content. What event type I'll be using in here? If I use "click/keydown" then tooltip gets applied every time I click/keydown on element but I want only once! .. thanks for your answer.
Wbdvlpr
hover (or mousein/mouseout) should be a good event for a tooltip. also, don't get all the elements on load, that's unnecessary when using event delegation.
geowa4