Is there a way to know if the user is using mobile or web?

I’ve seen a lot of recommendations SO:

But all of them have disadvantages. Is there one that is safer and commonly used in these days?

I would recommend against user agent sniffing — these are easy to spoof.

Why do you want to detect mobile users? Do you want to add/remove certain functionality depending on whether someone is on a mobile device?

Normally media queries and/or feature detection is the way to go.

6 Likes

Sorry for replying late. I’m using select2 but it’s hard to use it when using mobile. I want to detect the user if it is using mobile so that I can hide select2 and replace it with a normal select.

Select2 is an absolute drama when it comes to scaling. That’s why at work we recently switched to Choices. We tried to get select2 to play nice for hours and in the decided to give up.

2 Likes

Thanks for the suggestion but the native select is so much easier to control when using any touch screens.

Could you elaborate slightly. Is it hard to use because of the screen dimensions, or does the lack of a mouse make it difficult to use? Or something else?

Sorry, just read your reply to Rémon.

It shouldn’t be hard to detect a touch screen and initialize Select2 accordingly:

function is_touch_device4 {
  if ("ontouchstart" in window || window.TouchEvent) return true;
  
  if (window.DocumentTouch && document instanceof DocumentTouch) return true;

  const prefixes = ["", "-webkit-", "-moz-", "-o-", "-ms-"];
  const queries = prefixes.map(prefix => `(${prefix}touch-enabled)`);

  return window.matchMedia(queries.join(",")).matches;
}

if (!is_touch_device()) // initialize select2

However, this will catch iPads, laptops with a touch screens etc. To avoid this, you could query the viewport size and combine it with the above to make the decision about which version to display.

2 Likes

They will probably want the basic select anyway as tablets vary greatly in size and ease of use.

You could use the hover media query (modern browsers only).

const canHover = !matchMedia("(hover: none)").matches;
if (canHover) {
  document.body.classList.add("can-hover");
}
$(document).ready(function () {
  $(".can-hover .js-example-basic-single").select2();
});

2 Likes

That’s much nicer. Good job :slight_smile:

1 Like

@marks567217, it has already been advised against browser sniffing, and the OP has been given a satisfactory approach. Perhaps you can explain why you think browser sniffing is a good idea?

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.