Adding mobile swipe actions to a touch screen device.
When I first started this web site I obviously wanted to add some “nice” touches as at it’s core it is a marketing site for my freelance work. One of the things I wanted was a menu that slides out from the side. I actually did most of the work using CSS but obviously still needed JS to actually fire the css (addClass) to open and close the menu.
The actual CSS for the transition is really not complicated, I am using sass:
#primary-sidebar{ position: fixed; overflow-x: hidden; overflow-y: hidden; top: 0; right: 0; height: 100%; max-width: 100%; z-index: 99; box-sizing: border-box; background: #FFF; &.closed{ padding: 0; width: 0; } &.open{ width: 300px; overflow-y: scroll; } }
And the js to open and close the menu:
$('.menu-button.closed').click(function(){ $(this).addClass('open'); $(this).removeClass('closed') $("#primary-sidebar").addClass('open'); $("#primary-sidebar").removeClass('closed'); }); $('.menu-button.open, #close-sidebar').click(function(){ $(this).addClass('closed'); $(this).removeClass('open') $("#primary-sidebar").addClass('closed'); $("#primary-sidebar").removeClass('open'); });
So far, so good.
But the first time I showed this web site to a friend he viewed it on his mobile device, and upon opening the menu the first thing he tried to do was close it with a swipe. I was quick to say “oh yeah, I have not added the swipe action yet”.
So being a jQuery user the first road I went down was to add jQuery mobile, which to be honest seemed a little overkill just for the “swiperight” function! Upon enqueuing the jQuery mobile library the first thing I saw happening was the lib add new classes to inputs & other elements and in some cases breaking the design. Not wanting to re-build my site just to use jQuery mobile’s “swiperight” function I decided to look into a Vanilla JS solution.
After much head scratching and google searching I decided to use the below vanilla JS (yes with a little jQuery added) to give the swipe right capability to my sidebar/menu:
var touchstartX = 0; var touchstartY = 0; var touchendX = 0; var touchendY = 0; var gestureZone = document.getElementById('primary-sidebar'); gestureZone.addEventListener('touchstart', function(event) { touchstartX = event.changedTouches[0].screenX; touchstartY = event.changedTouches[0].screenY; }, false); gestureZone.addEventListener('touchend', function(event) { touchendX = event.changedTouches[0].screenX; touchendY = event.changedTouches[0].screenY; handleGesture(); }, false); function handleGesture() { var swiped = 'swiped: '; if (touchendX > (touchstartX + 100)) { //swipe right $('.menu-button.open, #close-sidebar').addClass('closed'); $('.menu-button.open, #close-sidebar').removeClass('open') $("#primary-sidebar").addClass('closed'); $("#primary-sidebar").removeClass('open'); } }
So this is how I achieved the sidebar/menu on this site, I hope this helps someone in the future.