tags:

views:

225

answers:

3

In javascript, what are the pro's and con's of encoding an onclick event in the DOM and in the HTML itself?

Which, if either, is better than the other and why?

+2  A: 

Your question almost answers itself when you refer to "the HTML itself".

JavaScript is not HTML -- Keeping the HTML and the JavaScript in separate locations is a benefit all by itself. Makes it easier to (humanly) read the HTML, and keeping all the JS in the same location makes it easier to track everything down all at once.

Michael Paulukonis
A: 

Attaching events to an CSS-style ID (or classes), as Jquery does so well, means that if you don't have JS enabled, it will automatically fall through to any links that are referenced. That's good practice, and will help to make sure that your page works in even quite simple browsers, such as some mobile handsets.

It's also good practice to layer the underlying data (the HTML), presentation (CSS) and behaviour (Javascript). Changing individual layers is a lot easier if they are well structured.

Alister Bulman
+1  A: 

It is better to write your Javascript in Javascript, as OtherMichael says. It is even better to use proper DOM events (addEventListener and attachEvent) rather than on_____, in order to avoid conflicts and allow multiple callbacks for the same event.

eyelidlessness