Skip to content

Instantly share code, notes, and snippets.

@martinmev
Last active August 29, 2015 14:16
Show Gist options
  • Save martinmev/4695cb3b746bb2bc63e1 to your computer and use it in GitHub Desktop.
Save martinmev/4695cb3b746bb2bc63e1 to your computer and use it in GitHub Desktop.
Detection (Javascript): Click (Desktop) or Touch (Touch device)?
<html>
<body>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script language="javascript">
mouseOverTime = 0;
mouseDownTime = 0;
isTouchDevice = null;
function getTime() {
var d = new Date();
return (d.getTime());
}
function mouseOverSetTime() {
if (isTouchDevice === null) {
mouseOverTime = getTime();
}
return true;
}
function mouseDownSetTime() {
if (isTouchDevice === null) {
mouseDownTime = getTime();
var difference = mouseDownTime - mouseOverTime;
if (difference < 50) {
isTouchDevice = true;
runOnTouchDevice();
document.cookie="isTouchDevice=1;path=/"
} else {
runOnNonTouchDevice();
document.cookie="isTouchDevice=0;path=/"
}
}
return true;
}
if ((document.cookie.search("isTouchDevice=1")) < 0) {
$(window).mouseover(mouseOverSetTime);
$(window).mousedown(mouseDownSetTime);
} else {
if ((document.cookie.search("isTouchDevice=1")) < 0) {
runOnNonTouchDevice();
isTouchDevice = false;
} else {
runOnTouchDevice();
isTouchDevice = true;
}
}
function runOnTouchDevice() {
var txt = document.getElementById('text');
txt.innerHTML = 'Touch device ' + mouseOverTime + ' ' + mouseDownTime + ' ' + (mouseDownTime - mouseOverTime);
}
function runOnNonTouchDevice() {
var txt = document.getElementById('text');
txt.innerHTML = 'Desktop ' + mouseOverTime + ' ' + mouseDownTime + ' ' + (mouseDownTime - mouseOverTime);
}
</script>
<h3>Click me</h3>
<h4 id="text"></h4>
<h1><a href="#">Xxxix xxxxx </a></h1>
<input type="text" name="sss" value="sss">
<input type="submit" value="6660000">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment