Reputation: 3009
I've learned that you can declare event handlers within either the HTML or the Javascript. My question is, is it better to do so in the Javascript or the HTML? Does it make a difference? If so, why?
Upvotes: 1
Views: 105
Reputation: 147343
It very much depends on your requirements. Adding an inline listener is no more difficult than adding a class or id, so whether you add them at the server (i.e. inline) or client (dynamically) depends on what suits a particular case. Having them in–line makes it clear to anyone maintaining the code where the listeners are just by looking at the server code or generated HTMl. Otherwise, they must search through script files to find out where they are.
Just use whatever is mote efficient for you.
Upvotes: 0
Reputation: 298056
Almost always JavaScript. It's cleaner, easier to maintain and separates the HTML from the JavaScript.
For example, you could write this:
<button onclick="do_something(this)">Button 1</button>
<button onclick="do_something(this)">Button 2</button>
<button onclick="do_something(this)">Button 3</button>
<button onclick="do_something(this)">Button 4</button>
Or you could leave the HTML as just HTML and bind the event handler from within your script:
$('button').click(function() {
// Do something
});
Upvotes: 1