Just now I delivered a project during the making of which I noted a feature of event bubbling that, though totally logical, came as a surprise to me. No doubt someone else will be surprised, too, and may even be able to use it in a project.
The project was an adaptation of my Site Survey script that's treated in chapter 6 of the book. In the standard script, a survey popup is opened as soon as the user clicks anywhere. However, for this version of the script I had to implement a special bar with a Yes/No option in which the user can indicate whether he wants to participate in the survey. Only when the user clicks Yes (or when he doesn't answer on three consecutive pages) is the popup opened.
I open the popup through my
Now the event is set for the bubbling phase: ie. any time a user clicks anywhere on the page, onclick event handlers of the element she clicks on are handled first (if any), after which the click event bubbles up to the document and my
ST_openPopup() function is executed. Usually I set this event handler immediately, but in the current version I set it only after the user has agreed to the survey.
The Yes/No buttons both have an onclick event handler, too. Appropriate actions are taken, and then the special bar with the buttons disappears.
The appropriate action on the Yes button is, among others, setting the onclick event handler on the document. When I tested this bit of the script, the popup opened as soon as I clicked on the Yes button. I'd expected I'd have to code this explicitly, but event bubbling took care of the dirty bits for me. What a pleasant surprise.
Picture the situation:
Useful, isn't it? And totally logical, once you stop to think about it.
However, later in the project I removed the button bar onclick, too. All of a sudden the popup stopped appearing as soon as I clicked on the Yes button. That's logical, too, though it took me five anguished minutes to track down the source of this apparent bug.
The solution was simple: delay the removal of the button bar by 100 milliseconds (
setTimeout). Now the event first bubbles up to the document and the popup is opened. Afterwards the bar can be safely removed.
All in a day's work.
I’m speaking at the following conferences:
Comments are closed.