0
function updateText(){
    alert(fontsize.options[fontsize.selectedIndex].value);
}

var fontsize = document.getElementById("fontsize");
fontsize.addEventListener('onChange','updateText',false);  

This is my JavaScript to handle the selection of font sizes on my webpage. However, nothing happens when I select different values in the dropdown.

There are no errors in the console log, either.

So, my questions are:
1. Why won't it work ?
2. Why is using event delegation model recommended over <select onchange="someMethod()">

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
An SO User
  • 24,612
  • 35
  • 133
  • 221

2 Answers2

4

Two problems:

  1. The event is called change, not onchange. onchange is the name of an HTML attribute and a DOM property.

  2. You have to pass a function to addEventListener, not a string.

So

fontsize.addEventListener('change', updateText, false);

should work.

It seems you are mixing inlineor traditional event handlers with advanced event handlers.

Equivalent inline event handler:

<select id="fontsize" onchange="updateText()">

or (don't do that):

fontsize.setAttribute('onchange', 'updateText()');

Unless you are only prototyping something, using inline event handlers is generally not a good idea, see below.

Equivalent traditional event handler:

fontsize.onchange = updateText;

Why is using event delegation model recommended over <select onchange="someMethod()">

This has nothing to do with event delegation. Event delegation is a concept independent from the way the event handlers are bound. For a practical reason not to use inline event handlers, see my answer here onclick="" vs event handler.

I also recommend to read the articles on quirksmode.org which in my opinion explain everything you need to know about event handlers.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I am not mixing them. I always use the `addEventListener`. The question is : why does everyone recommend that ? :) – An SO User Mar 23 '14 at 02:41
  • @LittleChild: Mixing in the sense of you are using one as if it were the other. E.g. you are using onchange which is an attribute/property of HTML/DOM elements, not an event, and you are passing a string instead of a function. If you follow the links, you will get a pretty good idea about the advantages and disadvantages of each of those methods. I also updated my answer. – Felix Kling Mar 23 '14 at 02:54
0

Because it should be

fontsize.addEventListener('change', updateText, false);

Not onChange.

The Alpha
  • 143,660
  • 29
  • 287
  • 307