Javascript/DOM event name convention

roy riojas picture roy riojas · Sep 28, 2013 · Viewed 12.5k times · Source

When I started doing web development, I realized Javascript event names were all in lower case with no separators, i.e. "mousedown", "mouseup", etc. And when working with the jQuery UI library, I noticed they also use the same convention; i.e. "dropdeactivate" as in the following example

$( ".selector" ).on( "dropdeactivate", function( event, ui ) {} )

While this works well for names that are only 2 or 3 words, it is really awful for names with more words on it.

Despite of this I followed that convention too when I have to fire custom (synthetic) events that I created, until recently when I decided it was better to start using some form of separator. Now I use something like "drop:deactivate", or "app:ready".

on iOS apple recently added this event for the HTML 5 Airplay API, and I agree with the autor of this post http://www.mobilexweb.com/blog/safari-ios7-html5-problems-apis-review when he says:

I think "webkitcurrentplaybacktargetiswirelesschanged" has won the record: the longest JavaScript event name ever.

What is the reason behind this weird convention? why not use any form of separator or camelCase convention to name the events in a more readable way?

I think there is a reason for that, lot of clever people worked on this... But after a while I'm still wondering why?

Answer

raina77ow picture raina77ow · Sep 28, 2013

Unfortunately, it's not so simple when you deal with legacy conventions. And DOM Events have a lot of history behind them.

Here's how type attribute of Event is defined in DOM2 Events specification:

Interface Event (introduced in DOM Level 2)
type (of type DOMString, readonly)

The name of the event (case-insensitive). The name must be an XML name.

The reasoning behind this, I suppose, is explained by this paragraph in the same doc:

In HTML 4.0, event listeners were specified as attributes of an element.[...] In order to achieve compatibility with HTML 4.0, implementors may view the setting of attributes which represent event handlers as the creation and registration of an EventListener on the EventTarget.

Now, while the stance has changed in DOM3 (where event names are case-sensitive), the original approach is, I suppose, ofter considered to be the safest bet - so one won't have to depend on user agents' correctness (check this discussion and this funny issue as examples).

Note that W3C itself has registered a whole slew of PascalCased events in DOM2 (all the MutationEvents, DOMActivate, DOMFocusIn and DOMFocusOut).