Mouse scroll event support for Swipebox

Javascript library Swipebox is commonly used in different galleries in spite of lack of support — last commit was several years ago. Nevertheless we can add mouse scroll support.

Here is a patch, created against the version of Swipebox used in «Responsive Gallery with lightbox» plugin for WordPress (differs from vanilla Swipebox):

--- D:/user/Documents/responsive-gallery-with-lightbox/lightbox/swipebox/jquery.swipebox.js	Sat Oct 27 11:30:24 2018
+++ D:/user/Documents/jquery.swipebox.js	Mon Oct 29 23:05:23 2018
@@ -52,6 +54,20 @@
             return ui;   
         }
 
+		// This function checks if the specified event is supported by the browser.
+		// Source: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
+		function isEventSupported(eventName) {
+			var el = document.createElement('div');
+			eventName = 'on' + eventName;
+			var isSupported = (eventName in el);
+			if (!isSupported) {
+				el.setAttribute(eventName, 'return;');
+				isSupported = typeof el[eventName] == 'function';
+			}
+			el = null;
+			return isSupported;
+		}
+		
 		plugin.init = function() {
 
 			plugin.settings = $.extend( {}, defaults, options );
@@ -207,6 +223,7 @@
 
 				// Devices can have both touch and keyboard input so always allow key events
 				$this.keyboard();
+				$this.mouse();
 
 				$this.animBars();
 				$this.resize();
@@ -499,6 +516,34 @@
 			},
 
 			/**
+			 * Mouse navigation
+			 */
+			mouse : function () {
+				var wheelEvent = isEventSupported('mousewheel') ? 'mousewheel' : 'wheel';
+				var $this = this;
+				$( window ).bind( wheelEvent, function( event ) {
+					event.preventDefault();
+					//event.stopPropagation();
+					
+					var oEvent = event.originalEvent;
+					var delta  = oEvent.deltaY || oEvent.wheelDelta;
+					
+					// deltaY for wheel event
+					// wheelData for mousewheel event
+
+					if (delta > 0) {
+						// Scrolled up
+						$this.getNext();
+					} else if (delta < 0) {
+						// Scrolled down
+						$this.getPrev();
+					}
+					
+				} );
+			},
+			
+			/**
 			 * Navigation events : go to next slide, go to prevous slide and close
 			 */
 			actions : function () {
@@ -759,6 +804,9 @@
 			 */
 			destroy : function () {
 				$( window ).unbind( 'keyup' );
+				// need to check which event to unbind the same way as having binded it
+				var wheelEvent = isEventSupported('mousewheel') ? 'mousewheel' : 'wheel';
+				$( window ).unbind( wheelEvent );
 				$( 'body' ).unbind( 'touchstart' );
 				$( 'body' ).unbind( 'touchmove' );
 				$( 'body' ).unbind( 'touchend' );

You can download it here: swipebox_mouse_scroll

You can leave a response, or trackback from your own site.

Leave a Reply