From a Drupal perspective, why is it considered improper to directly add an onclick attribute to an HTML element instead of using a Javascript behavior?

  • I took the liberty to rewrite this. The original was subjective, and I think this is more focused an answerable. 1. I didn't look, but this may be a duplicate. 2. For those answering, avoid "And also ..." answers that only build on other answers. Those will be deleted. – mpdonadio Dec 29 '15 at 22:30

There's a good answer in the JavaScript subreddit on reddit here. To summarise, here are the reasons provided:

  • tight coupling between presentation and behavior
  • code runs in the global scope
  • makes testing and debugging difficult
  • defies progressive enhancement
  • quickly becomes hard to maintain
  • also it will unbind any previously assigned click handlers which might be an unwanted side effect

Maintainability and testability are the major killers for me here.

There's not much more to add to give a Drupal specific answer. The only two things that comes to mind are the following:

  1. Behaviours are automatically re-applied to any content loaded via AJAX, so if you have an AJAX powered view the click handler will be rebound for you without having to have the function in the global scope.

  2. You don't have to try and locate templates, or hack away at anything just to add a new attribute to an element. For example, if you want a click handler on a node title link, you have to update the template. If you then add a new view mode, but still want to have the click handler listening, then you need to ensure the onClick is on that element as well - this increases the maintenance time and risk of error. If you just use a behaviour, then you can hook onto the title link class and it'll work everywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.