Firing HTML events

In all this time doing client side Javascript, I never had the need to fire HTML events, right until this day.

It all started with this simple task: intercept a form submission, process it to a custom URL which provides additional data to fill in the form, and afterward submit it to the action provided in the form (without intercepting it the second time). I had gone with the straight forward approach.

Can you spot the (possible) problem? Neither did I at first. I’ve managed to have the form work through the first submission, but couldn’t make it execute the second one. So as my nature goes, I’ve got to lengths to speculate that a form could not be submitted if once the event was stopped from propagating.

It’s crazy right, but that is one of my main traits (if we may call them so), always being skeptic about various implementations[1].

Being pressured by time I had to do a workaround, and had me googleing about methods to call native events (Prototype can only fire custom events). One led to another and I got to this article about firing Javascript events and the following nifty function to add to my library:

Seeing it so simple I obviously wondered why Prototype hasn’t implement it already (version 1.7). As it turns out it’s not that easy to implement across all browsers.

Excluding some browsers[2] wouldn’t have been a big impact on me, but fortunately at the moment of reading that I had already found the real reason in my issue (and you would have as well if you’ve read the article from where I’ve got the function), and it is exactly this line.

Without other context it would be baffling for a time, the real reason why it fails is because inside the form I have the submit field which has the name submit. As you should know form fields can be referred by index, name or id. In my case:

While, I for one was already aware of this, I did found it quite awkward that no Javascript (TypeError) exception was thrown, given I was trying to call an element as a function. Fuckin’ TypeErrors, how do they work?

Bottom line is that you can call native HTML events (for major browsers) and that it’s good to have your memory refreshed from time to time.

  1. As the time I got skeptic (for right reasons) about the web PUSH implementations, which are actually nothing more than PULLS with a long timeout.
  2. Main browser vendors would work with the fireEvent function

Filed under Code