views:

58

answers:

3

Suppose I have a <select> element on my HTML page, and I want to run some Javascript when the selection is changed. I'm using jQuery. I have two ways to associate the code with the element.

Method 1: jQuery .change()

<select id='the_select'>
<option value='opt1'>One</option>
<option value='opt2'>Two</option>
</select>

<script>
$('#the_select').change(function() {
  alert('Changed!');
});
</script>

Method 2: onChange attribute

<select id='the_select' onchange='selectChanged();'>
<option value='opt1'>One</option>
<option value='opt2'>Two</option>
</select>

<script>
function selectChanged() {
  alert('Changed!');
}
</script>

I understand the different modularity here: for example, method 1 keeps code references out of the HTML, but method 2 doesn't need to mention HTML ids in the code.

What I don't understand is: are there operational differences between these two that would make me prefer one over the other? For example, are there edge-case browsers where one of these works and the other doesn't? Is the integration with jQuery better for either? Does the late-binding of the code to the event make a difference in the behavior of the page?

Which do you pick and why?

A: 

I guess it would be easier to manage, bind and unbind when you don't hard code it. But hard coded ones are perfect for doing events in google maps for example. As it is hard to know at which stage of page load an element within in is available so binding from external scripts causes occasional problems.

But I mean from the separation of concern point of view not having event logic in markup is of course best

Another thing is about users connection. Sometimes having the events hard coded increases speed related problems where the user clicks on something which calls a not loaded function.

Also from the perspective of machines like screen readers or any device that doesn't have JS having event handling attributes, basically you are populating the page with non sense which increases the page size.

XGreen
+1  A: 

Well, have a read about

unobtrusive javascript

jAndy
+1  A: 

An advantage of method 1 is that binding the event does not disrupt any other JavaScript that may already have bound some code to the element. With method 2, if another code already binds the change event, you will have to change your HTML code.

Vincent Robert