JavaScript Trick: How to efficiently detect touch screen devices?
P粉877719694
P粉877719694 2023-08-20 15:26:32
0
2
554

I wrote a jQuery plugin for desktop and mobile devices. I'm wondering if there is a way to detect if a device has touchscreen capabilities using JavaScript. I'm using jquery-mobile.js to detect touch screen events and it works on iOS, Android, etc., but I also want to write a conditional statement based on whether the user's device has a touch screen or not.

Is this possible?

P粉877719694
P粉877719694

reply all (2)
P粉135292805

Update 2021

To see old answers: Check history. I decided to start from scratch because it was getting unmanageable when keeping history in posts.

My original answer said it was possible to use the same functions that Modernizr uses, but that is no longer valid because they removed the "touchevents" test in this PR:https://github.com/Modernizr/Modernizr/ pull/2432because this is a confusing topic.

Having said that, this should be a pretty good way to detect if a browser has "touch capabilities":

function isTouchDevice() { return (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)); }

But for more advanced use cases, people much smarter than me have written about this topic and I recommend reading these:

    P粉321584263

    Update: Before bringing the entire feature detection library into your project, please readblmstr's answerbelow, detecting actual touch support is more complex and Modernizr only covers basic use cases.

    Modernizris a lightweight method for detecting various features on any website.

    It just adds classes in html elements for each attribute.

    You can then easily target these features in CSS and JS. For example:

    html.touch div { width: 480px; } html.no-touch div { width: auto; }

    and JavaScript (jQuery example):

    $('html.touch #popup').hide();
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!