chriscrutt
chriscrutt

Reputation: 529

use ontouchstart() or onclick() depending on device

first, I know there are a few ways around this, such as making making the ontouchstart and onclick the same. But is there a way to check if the users has a smartphone/tablet/touchscreen device vs a laptop or computer, and change the function of ontouchstart to click? Here's an example of one way to solve it:

var touchScreen = false;
var touches = 0;
var clicks = 0;

document.addEventListener("touchstart", function() {
  touchScreen = true;

  function touch() {
    touches++;
    console.log(touches);
    console.log(clicks);
    document.getElementById("clicks").innerHTML = "touches = " + touches + ", clicks = " + clicks;
  }
  touch();

});

function click() {
  if (touchScreen === false) {
    document.addEventListener("click", function(event) {
      clicks++;
      console.log(touches);
      console.log(clicks);
      document.getElementById("clicks").innerHTML = "touches = " + touches + ", clicks = " + clicks;
    });
  }
}
click();
html {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
<h1><span id="clicks"></span></h1>

This code snippet shows that I've "identified" if it's a touchscreen device or not, and executed something based on that info. (FYI when you run code snippet make sure to click/tap on the blank space to receive an output)

However, I don't want to do this because I have many functions that rely on things such as <button onclick="click()">click</button>. I'd like to figure a simple way to just change the onclick part to ontouchstart if it's a touchscreen device. I use JavaScript for my scripting only, Thanks!

Also if you believe there is no way to do so, would there be a better way to check and execute code (with a click or touch) based on if the user has a touchscreen or other device?

edit:

I would normally just do click but some of the items on the page will probably be clicked at a fast rate, or at least faster than 300ms

Upvotes: 1

Views: 3107

Answers (2)

simlmx
simlmx

Reputation: 1333

The way I do this is I check if 'ontouchstart' in window and depending on the answer I either subscribe to touchstart or click.

Something like:

if ('ontouchstart' in window) {
  document.addEventListener("touchstart", () => { /*...*/ });
} else {
  document.addEventListener("click", () => { /*...*/ });
}

EDIT: Found more solutions on a related SO questions.

Upvotes: 1

caseyWebb
caseyWebb

Reputation: 2086

You could trigger a click event on touchstart, as such...

document.addEventListener('touchstart', (e) => {
  // prevent duplicate clicks
  e.preventDefault()

  e.target.dispatchEvent(new Event('click'))
))

Note though, this is exceptionally fragile because data on the event object — e — will not be propagated to the click events.

Upvotes: 0

Related Questions