Attila Naghi Attila Naghi - 19 days ago 6
Javascript Question

Prototype fire on change event issue

This is my js file content:

window.onload = function() {
obj = document.getElementById("_accountwebsite_id");
Event.observe(obj, 'change', function () {
alert('hi');
});
}


I want to fire the on change event for my dropdown:
_accountwebsite_id
. The prototype library it is loaded before this file. I got no errors in the console. Where am i wrong ? thx

Answer

You're doing a lot of extra work here that Prototype does for you. First off, setting the document's onload method not only is really old-school, it also will clobber any previously set observer on that event.

$(document).observe('dom:loaded', function( ... ){...});

...is the modern way to register one (or more) event listeners to the document load event.

Next, you're using getElementById here, which will work, but does not return a Prototype-extended object in some browsers.

$('element-id'); 

...will both get the element reference and extend it if your browser failed to respect every aspect of prototypal inheritance.

Finally, this whole thing can be made both simpler and more bulletproof by using a deferred observer. Imagine if your interface DOM was updated by Ajax -- that would make your observer miss the events fired by this select element, because it was not referring to the same (===) element, even if the ID matched.

$(document).on('change', '#_accountwebsite_id', function(evt, elm){
  alert(elm.inspect());
});

This observer will respond to any change event on an element with the correct ID, even if it was added after the observer was registered with the document.