views:

67

answers:

4

Hello,

I'm hopping that around the community of js developers we can have a consensus around this:

Should we declare or onclick, onkeyup... etc... events inside or outside our HTML document?

1) I do prefer to have them separate. True. 2) I'm also aware that HTML5 adds some new interactive elements on the game...

Regards, MEM

+2  A: 

Ideally if you can define your event code and attach those events to matching elements in separate JS files. Separate JS and HTML where ever possible.

Paul Hadfield
@ALL - What about the new come of html5. Can we do the same thing. Html5 has new events to play isn't it? I'm wondering if we can use that tecnique there as well...Behind this, I see that I'm not clear, about the nature of those events, either they belong to the DOM core, either they Belong to the javascript core isn't ?
MEM
I can't foresee HTML5 changing the recommendations for keeping JS code and HTML separate - hopefully people will just find better and clearer ways of doing it.
Paul Hadfield
@MEM: Nothing's changed with HTML5. You have new events, but the practice is the same.
musicfreak
And here I have the relation: The DOM is required by JavaScript scripts that wish to inspect or modify a web page dynamically. In other words, the Document Object Model is the way JavaScript sees its containing HTML page and browser state.
MEM
+2  A: 

Consider reading about Unobtrusive JavaScript and jQuery.

sanmai
+2  A: 

Writing event handlers inline has been a solidly bad idea for at least a decade.

Even accessing properties like 'element.onkeyup' is a pretty bad idea.

Use listeners. Better yet a framework.

EDIT: And here's why Tim Down's comment is ridiculous:

  1. If the rationale for ANY programming decision starts with "if you know you're only ever going to need..." then don't do it. Seriously.

  2. "All scriptable browsers" actually means IE5.5+ FF2+ Safari 3+ Opera 9+. That covers 99%+ of web users, and all those browsers support event listeners. Event listeners have major advantages over accessing event handler properties - the big one is that there can be more than one listener for any event. In modern Javascript programming this happens all the time. Special-casing your code to use an antiquated event handling system just because you can is an awful idea, hostile to really good ideas like using libraries and writing unobtrusive, consistent code.

  3. return false; is a solidly counterintuitive and anti-semantic way to mean "stop bubbling/propagating this event up/down the DOM tree." You know what is intuitive? Common expressions in library code like event.stop().

Triptych
thanks a lot for the listeners advice and framework one as well... I will try to learn more about event listeners.
MEM
Nonsense. If you know you're only ever going to need one event handler on `element` then `element.onkeyup` is the way to go. Firstly, it works in all scriptable browsers, and it works exactly the same (with the exception of where you get the event object from) in all of them. Secondly, the mechanism for preventing the default behaviour for the event is simply `return false;` in all browsers.
Tim Down
Got it. Well, the true is, I only need one. But I'm a stupid slow programmer that wishes to be as solid as possible, programmer. One day. :) That's the reason why, perhaps, I'm using PDO on a database with 100 records or less. Oh well... However, sometimes, we need to get it done, I'm just hoping that, when that day arrives on the js side, I can say: "Yes, I will code a js listener in no time" ;) But in order to do so... I do believe, we really need to suffer. And that's were I am know. :) K. Regards. :)
MEM
MEM: Sorry. My "Nonsense." was over-aggressive and directed at Triptych.
Tim Down
Triptych: 1. What? That sweeping statement is a recipe for over-designing and not getting anything done. You can't do anything without first defining your requirements. 2. I don't quite follow your point about particular browsers. Mine was that more browsers support event handler properties than support addEventListener/attachEvent. If yours was that browsers that don't support listeners are now largely irrelevant then I'd agree with that. Also, "antiquated" does not mean bad. 3. `return false` doesn't mean what you say. It means "don't perform the default browser action".
Tim Down
3. (continued) `return false` doesn't stop the event propagation. My original point about `return false` was that it's universally supported. I wasn't trying to say anything about whether `return false` is a sensible choice of syntax for doing what it does; I'm not certain `event.stop()` is any better (stop what exactly?), and in any case does not serve the same purpose.
Tim Down
@Triptych: event.stop is cross-browser? Don't you need a JS library to use it?
Marco Demajo
@Marco That's what I meant by "library code".
Triptych
+1  A: 

The current popular opinion is that everything must be unobtrusive, which means that event handler properties such as someElement.onclick = function(e) { ... }; are widely frowned upon and event handler attributes such as <input type="button" onclick="doSomething()"> are outright dismissed. In fact, there are valid uses for both.

The desire to separate behaviour (such as scripted event handlers) from content is a natural one and is a major consideration, but should not be the only consideration. As shown in the summary below, the three methods of creating event handlers have their own advantages and disadvantages, and in a particular situation, separation of behaviour and content may not be the overriding concern.

In conclusion, for a given task, use the simplest method that fits your needs.


Event handler properties

Example

myElement.onclick = function(e) { alert("Clicked"); };

These are particularly useful for assigning an event handler to an element that you create in script and are certain will only ever require one listener.

Advantages

  • Separates behaviour from content
  • Works in all scriptable browsers
  • Works the same in all browsers, apart from the issue of where the Event object comes from (window.event in IE, function parameter in other browsers)
  • Universally supported method of preventing the default browser behaviour using return false

Disadvantages

  • Allows only one listener for a particular object and event
  • On elements in the HTML source, handlers are typically not assigned until document is loaded

Event handler attributes

Example

<input type="button" value="test" onclick="alert('Clicked');">

This is the only approach that works when it matters that an element responds to an event before the document has finished loading (see http://peter.michaux.ca/articles/the-window-onload-problem-still for a longer discussion of this). Also, it's the easiest way to add event handlers.

Advantages

  • Works in all scriptable browsers
  • Works the same in all browsers
  • Works as soon as the element is rendered
  • Simplest way to add an event handler
  • Universally supported method of preventing the default browser behaviour using return false
  • On a very simple page, it's the most readable method
  • Standardized in the HTML 4 spec

Disadvantages

  • Mixes behaviour with content
  • Allows only one listener for a particular object and event

addEventListener/attachEvent

Example (attachEvent equivalent not shown)

myElement.addEventListener("click", function(e) { alert("Clicked"); }, false);

This is the only method that allows you to attach multiple listeners to a particular event on a particular object. addEventListener is standardized in the DOM Level 2 Events specification.

Advantages

  • Separates behaviour from content
  • Allows multiple event listeners
  • addEventListener is a modern standard, with support in IE 9 meaning that all current major browsers will support on release of IE 9

Disadvantages

  • Slightly complicated to implement correctly cross-browser
  • IE's attachEvent is not exactly equivalent to addEventListener
  • On elements in the HTML source, handlers are typically not assigned until document is loaded
Tim Down
-1? Please explain.
Tim Down
@Tim Down: +1 and BTW when you say that addEventListener/attachEvent is complicated to implement correctly cross-browser, it's not that true, it's probably because people got so used to use a JS library that don't even know anymore how simple it could be, have a look http://stackoverflow.com/questions/2631241/simple-javascript-to-mimic-jquery-behaviour-of-using-this-in-events-handlers and tell me your thoughts.
Marco Demajo
Marco: I've written cross-browser addEventListener/attachEvent wrappers before and it I agree that it isn't too hard, but there are a few issues that are not immediately apparent, such as the issue of `this` in the listener function and how you pass the Event object into the listener function. Both easily solved, but you need to know about them.
Tim Down