What's the best way to bind code to events in jQuery?
Suppose I have an element <select>
in my HTML page and I want to run Javascript when the selection changes. I am using jQuery. I have two ways to link code to an 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: the 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 stores links to code from HTML, but method 2 does not require mentioning HTML IDs in the code.
What I don't understand is: are there operational differences between the two that would make me prefer one over the other? For example, are there browsers with a brief case where one of these works and the other doesn't? Is the integration with jQuery improved? Does the late binding of the code to an event mean a change in page behavior?
What do you choose and why?
a source to share
I think it would be easier to manage, bind and unbind when you don't hardcode it. But hardcoded ones are ideal for executing events on Google maps, for example. Since it is difficult to understand at what stage of page load an element is available internally, so linking to external scripts causes irregular problems.
But what I mean is that the separation of concern point of view has no event logic in the markup, of course is better
Another thing about connecting users. Sometimes, when events are hardcoded, the problem-related speed increases when the user clicks on something that calls an unloaded function.
Also from the point of view of machines like screen readers or any device that doesn't have JS with event handling attributes, basically you fill the page with insensitive, which increases the page size.
a source to share