Mouse drag event support for SwipeBox

More precisely, I will tell how to add support of mousedown and mouseup events and how to use the difference of X coordinates to switch to the previous or to the next image in the gallery.

This handling might be more of academic interest.
I added two functions. The first one handles mouse down event and saves the X coordinate. The second one handles mouseup event when you release the button and calculates the difference. Based on the difference we switch to the previous or to the next image. Zero value causes no switching.
The result can be seen here: link
Note. The lines may differ from .js file of vanilla Swipebox, I edited the one from WordPress Responsive Gallery plugin.

--- 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	Sat Nov 10 13:30:36 2018
@@ -207,6 +207,7 @@
 
 				// Devices can have both touch and keyboard input so always allow key events
 				$this.keyboard();
+				$this.mouseDrag();
 
 				$this.animBars();
 				$this.resize();
@@ -499,6 +500,41 @@
 			},
 
 			/**
+			 * Mouse drag-based navigation
+			 */
+			mouseDrag : function () {
+				var $this = this;
+				// cordinates of click events
+				var x_mouse_down = -1;
+				var x_mouse_up = -1;
+				
+				$( window ).bind( "mousedown", function( event ) {
+					event.preventDefault();
+					event.stopPropagation();
+					
+					x_mouse_down = event.clientX;
+					
+				} );
+				
+				$( window ).bind( "mouseup", function( event ) {
+					event.preventDefault();
+					event.stopPropagation();
+					
+					x_mouse_up = event.clientX;
+					
+					delta_x = x_mouse_up - x_mouse_down;
+					//console.log("delta_x = " + delta_x);
+					if (delta_x > 0) {
+						$this.getPrev();
+					} else if (delta_x < 0) {
+						$this.getNext();
+					}
+					x_mouse_down = -1; 
+				} );
+			},
+			
+			/**
 			 * Navigation events : go to next slide, go to prevous slide and close
 			 */
 			actions : function () {
@@ -759,6 +795,11 @@
 			 */
 			destroy : function () {
 				$( window ).unbind( 'keyup' );
+			
+				$( window ).unbind( 'mousedown' );
+				$( window ).unbind( 'mouseup' );
+				
 				$( 'body' ).unbind( 'touchstart' );
 				$( 'body' ).unbind( 'touchmove' );
 				$( 'body' ).unbind( 'touchend' );

The patch can be downloaded: swipebox_mouse_drag.

Please take a look at another article on handling mouse scroll event:

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

Leave a Reply