Mobile active state
Testing different solutions for mobile active state handling
by HYEONGJINKIM
HTML
<h1>Desktop<h1>
<button class="css-hover">Button with :hover</button>
<h1>Mobile Option 1<h1>
<button class="css-active">Button with :active</button>
<h1>Mobile Option 2<h1>
<button class="js-class">Button with JS class</button>
CSS
* {
margin: 0;
padding: 0;
border: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
background-color: #eee;
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-tap-highlight-color: transparent;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
h1 {
margin: 10px;
}
button {
margin: 10px;
padding: 10px;
border-radius: 5px;
background: #ddd;
outline: 0;
}
button.css-hover:hover {
background: violet;
}
button.css-active:active {
background: teal;
}
button.js-class.active {
background: royalblue;
}
JavaScript
/*
* Code needed for :active solution (option 1)
*/
window.onload = function() {
if(/iP(hone|ad)/.test(window.navigator.userAgent)) {
document.body.addEventListener('touchstart', function() {}, false);
}
};
//-----------------------------------------------------------------------------
/*
* Code needed for JS solution (option 2)
*/
var timer, $el;
var events = 'ontouchstart' in window ? ['touchstart', 'touchmove touchend touchcancel'] : ['mousedown', 'mousemove mouseup'];
// support for IE touch events
if (window.navigator.pointerEnabled) {
events = ['pointerdown', 'pointermove pointerup pointercancel lostpointercapture'];
} else if (window.navigator.msPointerEnabled) {
events = ['MSPointerDown', 'MSPointerMove MSPointerUp MSPointerCancel MSLostPointerCapture'];
}
var start = function() {
if (timer) { return; }
$el = jQuery(this);
timer = window.setTimeout(function() {
$el.addClass('active');
}, 50);
};
var stop = function() {
if (!timer) { return; }
window.clearTimeout(timer);
timer = null;
$el = jQuery(this);
setTimeout(function() {
$el.removeClass('active');
}, 10);
};
$('body').on(events[0], 'button.js-class', start);
$('body').on(events[1], 'button.js-class', stop);