javascript bind an event handler to horizontal scroll

I wrote a jQuery plugin for you that lets you attach functions to the scrollh event.

See it in action at jsfiddle.net.

/* Enable "scrollh" event jQuery plugin */
(function ($) {
    $.fn.enableHScroll = function() {
        function handler(el) {
           var lastPos = el
              .on('scroll', function() {
                 var newPos = $(this).scrollLeft();
                 if (newPos !== lastPos) {
                     $(this).trigger('scrollh', newPos - lastPos);
                     lastPos = newPos;
                 }
              })
              .scrollLeft();
        }
        return this.each(function() {
            var el = $(this);
            if (!el.data('hScrollEnabled')) {
                el.data('hScrollEnabled', true);                 
                handler(el);
            }
        });
    }
}(jQuery));

It's this easy to use:

$('#container')
    .enableHScroll()
    .on('scrollh', function(obj, offset) {
        $('#info').val(offset);
    });

Please note that scroll events come very fast. Even if you click in the scrollbar to jump to a new position, many scroll events are generated. You may want to adjust this code to wait a short time and accumulate all the changes in position during that time before firing the hscroll event.


Answering from my phone, so unable to provide code at the moment.

What you'll need to do is subscribe to the scroll event. There isn't a specific one for vertical/horizontal.

Next, you'll need to get some measurements about the current display area. You'll need to measure the window.clientHeight and window.clientWidth.

Next, get window.top and window.left. This will tell you where position of the viewport is, ie if it's greater than 0 then scroll bars have been used.

It's pretty simple math from here to get what you need. If no one else has provided a code example in the next few hours I'll try to do so.

Edit: A bit further information.

You must capture the scroll event. You also need to store the initial window.top and window.left properties somewhere. Whenever the scroll event happens, do a simple check to see if the current top/left values differ from the stores value.

At this point, if either are different you can trigger your own custom events to indicate vertical or horizontal scrolling. If you are using jQuery, this is very easy. If you are writing js without library assistance, it's easy too but a little more involved.

Do some searches for event dispatching in js.

You can then write any other code you want to subscribe to your custom events without needing to tie them together with method calls.