Scroll and wheel

This is a truth universally acknowledged that one event handler is better than ten.
Usually, events bubble. That is, they are passed on to “upper” – parent – element levels, and higher and higher and higher. So, if you have, say, 10 buttons that need to process the same event, it might be easier to just add a listener on document level, and check the target coming with the event.

Simple case: there is a context menu. When a user scrolls outside of the menu, you want to hide it, because if the user is scrolling the page, it means he is not interested in whatever the menu offers. So it’s best to cancel it.

So, you want to add an onscroll handler; but it’s not on the menu. It is on everything that is not a menu.
Wait, but there can be hundreds of elements on that page. One can’t add that handler to all of them right? So you think, this is the case where I add it on the document level!

But the thing is, the onscroll event on the element doesn’t bubble up to the document. It happens too often, so if it did bubble, the quantity of events in a page would just slow it down unmercifully.

As it happens, there is an alternative. The wheel event does bubble. (But do not mix it up with the mousewheel event, which is non-standard and deprecated besides.) This event is supported in all major browsers (except opera), but in IE it can only be listened to through the addEventListener() method; there is no onwheel attribute on elements.

Advertisements

About Maryna Cherniavska

I have productively spent 10+ years in IT industry, designing, developing, building and deploying desktop and web applications, designing database structures and otherwise proving that females have a place among software developers. And this is a good place.
This entry was posted in javascript and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s