How best to associate code with events in jQuery?

Posted by Ned Batchelder on Stack Overflow See other posts from Stack Overflow or by Ned Batchelder
Published on 2010-05-05T12:04:22Z Indexed on 2010/05/05 12:08 UTC
Read the original article Hit count: 352

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about event-handling