Search code examples
javascriptprototypejsdom-events

How can I add an event observer for each element I find on the page?


I'm working with Prototype on a script to detect all Select Tags under a Div and then add an event/observer on each one!

Here is the code to find the Elements I need:

Event.observe(window, 'load', function() {
  var tab=$("product-options-wrapper").descendants();
  var attCode=[];
  var j=0;

  for (i=0;i<tab.length;i++) {
    if (tab [i].tagName =="SELECT") {
      attCode[j++]=tab[i].id
    }
  }
});

I have all the Ids I need. How can I add an observer (on change) for each one?

$(id).on("change", function(event) {
  alert(id+"__"+$(id).value);
});

Solution

  • Prototype supports event delegation out of the box. Event.on takes on optional second selector parameter. So in your case:

    $("product-options-wrapper").on('click', 'select', function(event, element) {
    
      // This callback will only get fired if you've clicked on a select element that's a descendant of #product-options-wrapper
      // 'element' is the item that matched the second selector parameter, in our case, the select.
    
      ....
    
    });
    

    That parameter can be any CSS selector string:

    $('my-element').on('click', '.some-class', function(event, element) { ... });
    

    Check out Element.select, too. That will condense the code in your original question down to essentially one line:

    $("product-options-wrapper").select('select');
    

    This one seems kind of confusing because your selector string is 'select' (you want all SELECT elements under #product-options-wrapper). You could also do:

    $$('#product-options-wrapper select');
    

    These both return an array of matched elements.

    HTH