[thelist] Javascript: onChange fires every time the page loads

Phil Turmel philip at turmel.org
Thu Apr 21 13:15:35 CDT 2005


Iain,

The fundamental difference between your code and the example at 
quirksmode is the assignment itself:

Either a bare function name is assigned:
window.onresize = register;

Or a complete function is declared:
window.onunload = function (e) {alert('Unload event'); register(e)};

In contrast to yours:
styleMenu[i].onchange = setStyle(styleMenu[i].value);

which *evaluates* the 'setStyle' function immediately and sets the event 
handler to the result (which doesn't work, since the *result* isn't a 
function).

When event functions are assigned this way, the only usable parameter to 
the event function is the *event* data structure, which you then have to 
analyze within the event function.  Then the function can figure out 
which element is involved and perform the corresponding operation.

First, change your assignment to:
styleMenu[i].onchange = setStyle;

Then, change your 'setStyle' function to lookup this.value instead of 
expecting an argument.  If you show us the actual 'setStyle' code, we 
might make more specific suggestions.

Quirksmode has a full explanation here:
http://www.quirksmode.org/js/this.html

HTH,

Phil

Iain Gardiner wrote:
> Hi guys,
> 
> Warning!  JS newbie coming through.  I have a problem with attaching 
> onchange handlers to menu options.  The full script I am referring to is 
> at http://www.firelightning.com/js/switcher.js and the specific function 
> is this:
> 
> /* FUNCTION: ATTACH ONCHANGE EVENT TO MENU */
> function menuSetup() {
>     var styleMenu = document.getElementById('styleMenu');
>     // Attach an onchange event to each menu option:
>     for (var i=0; i < styleMenu.length; i++) {
>         styleMenu[i].onchange = setStyle(styleMenu[i].value);
>     }
> }
> 
> Now, this function is called on page load and as far as I can tell this 
> should work by just telling the browser to listen for the onchange 
> event.  What actually happens is that when the page loads, the event is 
> fired for each menu option in turn instead of waiting for user input.  I 
> can't for the life of me work out why.  I don't see what fundamental 
> difference there is between my script and the examples at 
> http://www.quirksmode.org/js/events/window.html on PPK's site.
> 
> I really hope someone can help.  :)
> 
> Thanks,
> 
> Iain
> 



More information about the thelist mailing list