Reputation: 9076
Earlier I asked a question about embedding JS in a page, versus locating it in the head or at the end of the body, Embed Javascript in the body of the document?.
My question now is, what's the best way to handle binding JS to HTML DOM events? I could:
In some cases I realise I will have no choice, but in simple cases, I'm inclined to take the second option. For example, here's how I would like to initialise my auto-search bar:
<input id="auto-search" value="Search for person by name" onfocus="this.value=null"/>
This feels natural but the downside is that my JS is now spread throughout my HTML, not nicely tucked away in a single file. What do you do?
As a longer term approach I like the idea of RequireJS, but I'm not ready to look at it just yet.
Upvotes: 1
Views: 137
Reputation: 35790
One major reason not to inline your event handlers like that is that it won't work well with libraries like jQuery. jQuery does a lot of great stuff with event handling; for instance they normalize the event object that gets passed in your the event handler, so it looks the same no matter which browser your user has. Other major libraries with event handling functions do similar things as well.
If you hook up your events "inline" with on* attributes, jQuery (or whatever library you use) won't be aware of them, and thus won't be able to normalize the event object or easily unbind the events for you.
More broadly, there are general benefits to keeping Javascript in Javascript files. Not all of them apply to something this small, but still as a general practice I think most developers would recommend not using the on* attributes.
Upvotes: 1