1

Which is better practice on "simple" websites. (very few javascript actions)

a:To attach event/action/function onto an element (div/span/...)

like how this button and click event added to some div:

$( "#create-user" )
  .button()
  .click(function() {
  $( "#dialog-form" ).dialog( "open" );
  });

b:or in line have element action call a function.

<div id=calc onclick="doCalcFunc(this)">calc something</div>

This is questioned from someone that comes from more of a OO background, java/c#, so have found that prefer B, simple from easily finding what is happening. Maybe it might simply be learning more on web debug tools, but being able to click go to source on an element, and seeing, oh, when you click this element, it will run function X. As to method "A", which I would have to do a search on the source for some function which might be attached to the element ID, or type, or class, or some other indicator for the element.

5
  • 4
    Preference these days: en.wikipedia.org/wiki/Unobtrusive_JavaScript Commented Apr 22, 2013 at 14:00
  • Using inline JS is so 20 something...;-) Commented Apr 22, 2013 at 14:00
  • 11
    Almost universally, well-respected experts would prefer A. Commented Apr 22, 2013 at 14:00
  • 2
    a) because it separates the view from the code. Commented Apr 22, 2013 at 14:00
  • "or some other indicator for the element". I suggest researching the usage of sigils, see phabricator.com/docs/javelin/article/… Commented Apr 22, 2013 at 14:13

2 Answers 2

4

Even for a simple website, the format shown in Option A would be better since it seperates the code from the HTML Markup. This is also one of the main principles of Unobtrusive JavaScript.

In my experience it is much easier to replace and modify an event attached to an element using the HTML DOM, or a framework like JQuery, then it is to replace many lines of inline code in markup. Most of the websites I work on have dynamically generated content, and maintaining all of that code using inline functions would be a pain.

In addition, Option A (attaching the event onto an element) also allows you to use a variety of functions, like anonymous functions and various styles of closures. In Option B, doCalcFunc needs to be defined before the div element in order to work. Using Option A, the function can be defined when the function is attached to the div's event. This allows much more flexibility in initially coding, and maintaining the site in the future.

Sign up to request clarification or add additional context in comments.

1 Comment

"In Option B, doCalcFunc needs to be defined before the div element in order to work." That's not true. The function can be defined at any point as long as it's before the click event happens... though the function must be global.
1

While I would most of the time use JS based handler assignment, there are those times where handler attributes work nicely.

What's important is to not throw away any potential tool, but rather to know the pros and cons of both techniques, which I'll attempt to list below. I'm going to try to give each "con" a counterpoint for consideration.


Element attribute handlers

Pros

  • Handler is available immediately upon creation of the node (zero latency).
  • Assignment is very simple, and has extremely wide cross-platform support.
  • Provides a hook into the element that doesn't overlap CSS (using classes for both styling and behavior)
  • Immediate visibility in the markup of the behavior attached to the element.

Cons

  • Mixes behavior and presentation.
    • Counter: While true, it's really only an issue when embedding large amounts of JavaScript. A single function call is no more obtrusive than adding a class to the element.
  • The code is eval'd on every event.
    • Counter: This one actually is not true, but it's so commonly stated as a con, that I thought I'd include it. Truth is that it's eval'd once, when the page loads, just like the rest of the JavaScript.
  • If there are multiple elements with the same handler, you don't get to share a function, but rather each element gets a unique function.
    • Counter: This is true. Even if the function call is identical, a new function will be made per element, per event. But if there are several sharing the same handler, a case could be made for event delegation.
  • High maintenance. Changes to the function mean markup must be changed to match.
    • Counter: This is true, though adding handlers in JavaScript code can have similar issues with changes in class name, or with markup changes breaking DOM selection.
  • Only one handler can be assigned per element, per event type.
    • Counter: This is true, though you can have a single generic function that calls other functions, somewhat similar to how jQuery works under the hood.
  • There can be collisions with handlers assigned in JavaScript. When assigning an onclick="foo()" attribute, you're actually assigning a function to element.onclick. Since only one can be assigned per element, any changes to the property in JS will overwrite your handler.
    • Counter: This is true. And while this definitely needs to be taken into consideration, it shouldn't be used as grounds for dismissing inline or .onclick handlers entirely. There are plenty of situations where there will be no conflicts.

jQuery handler assigned in JavaScript code

Pros

  • jQuery makes it very simple and compatible.
  • No direct mixing of JavaScript with markup.
  • Changes to the handler are done entirely in JavaScript, and are less likely to require a repetitive change when multiple elements are involved.
  • Browser compatibility fixes are built in.

Cons

  • If the handler is assigned after the DOM is ready, there can be a period of time where the element is visible without its JavaScript behaviors.
    • Counter: While true, this is not often an issue. It's probably most relevant if you have a large page being sent over a slow connection. In those cases, you can embed the script closer to the element instead of waiting for the entire DOM.
  • Requires an overly complex DOM-ready solution.
    • Counter: Not really. While some choose to use such solutions, there's no reason why the script assigning the handler can't simply be placed at the bottom of the page.
  • When adding the first handler to an element, jQuery actually makes another function, even if the actual handler is shared among multiple elements.
    • Counter: While this is true, it's only true for the first handler assigned to an element. Additional handlers assigned get to share the "under the hood" one that jQuery made, so the extra overhead is only on the first one, per element.
  • Has its own "obtrusive" issues, where classes may be used by both JavaScript and CSS teams, allowing for one or the other to break code with a class change.
    • Counter: While true, in such situations multiple classes can be used with naming conventions, giving hands-off indicators to each team.
  • The behavior isn't visible from the markup.
    • Counter: If classes are used specifically for handler assignment, and good naming conventions are used, they can be just as descriptive as inline handlers.
  • Adding a class just for JavaScript is no less obtrusive than adding an inline handler.
    • Counter: While it's true that doing class="click_handler" isn't much different than doing onclick="handler(this)", with a well designed DOM, it's very likely that you'll be able to do your assignment without the need for classes at all. (Though you then lose the visibility benefit in markup.)

So while trying hard to avoid any sort of religious adherence to either approach, I've tried to offer something of an overview of some of the considerations both ways.

While you may find yourself using the more popular DOM-ready approach to assigning handlers much of the time, there are those situations where an inline handler can fit the bill nicely, especially if the zero latency aspect is important.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.