<p>I see 2 main ways to set events in JavaScript:</p>

<ol>
<li><p>Add an event directly inside the tag like this:</p>

<p><code>&lt;a href="" onclick="doFoo()"&gt;do foo&lt;/a&gt;</code></p></li>
<li><p>Set them by JavaScript like this:</p>

<p><code>&lt;a id="bar" href=""&gt;do bar&lt;/a&gt;</code></p></li>
</ol>

<p>and add an event in a <code>&lt;script&gt;</code> section inside the <code>&lt;head&gt;</code> section or in an external JavaScript file, like that if you're using <strong>prototypeJS</strong>:</p>

<pre><code>Event.observe(window, 'load', function() {
    $('bar').observe('click', doBar);
}
</code></pre>

<p>I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases).</p>

<p>The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag.</p>

<p>Which method is the best?</p>

<p>A killer answer will be fully appreciated!</p>

[{'answer_id': 34130, 'author': 'Polsonby', 'author_id': 137, 'author_profile': 'https://Stackoverflow.com/users/137', 'pm_score': 0, 'selected': False, 'text': '<p>Libraries like YUI and jQuery provide methods to add events only once the DOM is ready, which can be before window.onload. They also ensure that you can add multiple event handlers so that you can use scripts from different sources without the different event handlers overwriting each other.</p>\n\n<p>So your practical choices are;</p>\n\n<p>One. If your script is simple and the only one that will ever run on the page, create an init function like so:</p>\n\n<pre><code>window.onload = function () {\n    init();\n}\nfunction init() {\n    // actual function calls go here\n    doFoo();\n}\n</code></pre>\n\n<p>Two. If you have many scripts or plan to mashup scripts from different sources, use a library and its <code>onDOMReady</code> method to safely add your event handlers</p>\n'}, {'answer_id': 34141, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 3, 'selected': False, 'text': "<blockquote>\n  <p>I think the first method is easier to read and maintain</p>\n</blockquote>\n\n<p>I've found the opposite to be true. Bear in mind that sometimes more than one event handler will be bound to a given control.</p>\n\n<p>Declaring all events in one central place helps to organize the actions taking place on the site. If you need to change something you don't have to search for all places making a call to a function, you simply have to change it in one place. When adding more elements that should have the same functionality you don't have to remember to add the handlers to them; instead, it's often enough to let them declare a class, or even not change them at all because they logically belong to a container element of which all child elements get wired to an action. From an actual code:</p>\n\n<pre><code>$$('#itemlist table th &gt; a').invoke('observe', 'click', performSort);\n</code></pre>\n\n<p>This wired an event handler to all column headers in a table to make the table sortable. Imagine the effort to make all column headers sortable separately.</p>\n"}, {'answer_id': 34163, 'author': 'Thomas Lötzer', 'author_id': 3587, 'author_profile': 'https://Stackoverflow.com/users/3587', 'pm_score': 3, 'selected': True, 'text': "<p>In my experience, there are two major points to this:</p>\n\n<p>1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to start searching for the calls and don't immediately know where to look.</p>\n\n<p>2) The second kind, i.e. <code>Event.observe()</code> has advantages when the same or a very similar action is taken on multiple events because this becomes obvious when all those calls are in the same place. Also, as Konrad pointed out, in some cases this can be handled with a single call.</p>\n"}, {'answer_id': 34179, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 1, 'selected': False, 'text': '<p>You can also use addEventListener (not in IE) / attachEvent (in IE).</p>\n\n<p>Check out: <a href="http://www.quirksmode.org/js/events_advanced.html" rel="nofollow noreferrer">http://www.quirksmode.org/js/events_advanced.html</a></p>\n\n<p>These allow you to attach a function (or multiple functions) to an event on an existing DOM object.  They also have the advantage of allowing un-attachment later.</p>\n\n<p>In general, if you\'re using a serious amount of javascript, it can be useful to make your <em>javascript</em> readable, as opposed to your html.  So you could say that <code>onclick=X</code> in the html is very clear, but this is both a lack of separation of the code -- another syntactic dependency between pieces -- and a case in which you have to read both the html and the javascript to understand the dynamic behavior of the page.</p>\n'}, {'answer_id': 34212, 'author': 'Matt Sheppard', 'author_id': 797, 'author_profile': 'https://Stackoverflow.com/users/797', 'pm_score': 2, 'selected': False, 'text': "<p>I believe the second method is generally preferred because it keeps information about action (i.e. the JavaScript) separate from the markup in the same way CSS separates presentation from markup.</p>\n\n<p>I agree that this makes it a little more difficult to see what's happening in your page, but good tools like firebug will help you with this a lot. You'll also find much better IDE support available if you keep the mixing of HTML and Javascript to a minimum.</p>\n\n<p>This approach really comes into its own as your project grows, and you find you want to attach the same javascript event to a bunch of different element types on many different pages. In that case, it becomes much easier to have a single pace which attaches events, rather than having to search many different HTML files to find where a particular function is called.</p>\n"}, {'answer_id': 34293, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>My personal preference is to use jQuery in external js files so the js is completely separate from the html. Javascript should be unobtrusive so inline (ie, the first example) is not really the best choice in my opinion. When looking at the html, the only sign that you are using js should be the script includes in the head.</p>\n\n<p>An example of attaching (and handling) events might be something like this</p>\n\n<pre><code>var myObject = {\n\n    allLinkElements: null,  \n\n    init: function()\n    {\n        // Set all the elements we need\n        myObject.setElements();\n\n        // Set event handlers for elements\n        myObject.setEventHandlers();\n    },\n\n    clickedLink: function()\n    {\n        // Handle the click event\n        alert('you clicked a link');\n    },\n\n    setElements: function()\n    {\n        // Find all &lt;a&gt; tags on the page\n        myObject.allLinkElements = $('a');\n\n        // Find other elements...\n    },\n\n    setEventHandlers: function()\n    {\n        // Loop through each link\n        myObject.allLinkElements.each(function(id)\n        {   \n            // Assign the handler for the click event\n            $(this).click(myObject.clickedLink);\n        });\n\n        // Assign handlers for other elements...\n    }\n}\n\n// Wait for the DOM to be ready before initialising\n$(document).ready(myObject.init);\n</code></pre>\n\n<p>I think this approach is useful if you want to keep all of your js organised, as you can use specific objects for tasks and everything is nicely contained. </p>\n\n<p>Of course, the huge benefit of letting jQuery (or another well known library) do the hard work is that cross-browser support is (largely) taken care of which makes life much easier</p>\n"}]
['https://Stackoverflow.com/questions/34126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3122/']