Js определить тип устройства планшет
Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS @media attribute? I would like to run a different script if the browser is on a handheld device.
The jQuery $.browser function is not what I am looking for.
jQuery does not, and cannot do everything. It is provides cross-browser DOM traversal and manipulation, simple animation and ajax between browsers, and creates a skeleton framework for plugins to build upon. Please be aware of jQuery's limitations before asking specifically for a jQuery solution.
User agents are constantly moving targets, everyone reading this post should be very wary of user agent sniffing
What's a 'mobile' device? Is it a device that supports touch (including Chrome Pixels and Windows 8 laptops with mice)? Is it a device with a small screen (what about retina iPads)? Is it a device with a slow CPU? Or a device with a slow internet connection? Depending on what you want to do the answer to this question will vary. To target screen resolution or touch is easy. If you want to serve up smaller content or less intensive JS for some devices, then there's no silver bullet. Test for window.navigator.connection and fall back to (nasty, bad, ill-advised) userAgent sniffing. My 2 cents.
@Cole"Cole9"Johnson My point exactly. 'Mobile' seems to be used as an umbrella term for touch, slow CPU, slow network and small screen. But none of these are perfect assumptions. I believe that considering these individually will result in a better product than designing for some vague concept of 'mobile'. Hence me posing that question to the OP.
Browser usage:
Обновление 2021 года
Этот материал написан в 2018 году. Что изменилось более чем за 2 года после его публикации?
Разработчики веб-браузеров действуют гораздо быстрее тех, кто занимается стандартами. И возникает такое ощущение, что они, скорее всего, ещё до выхода официального стандарта, сделают медиазапросы, использующие pointer , any-pointer , hover и any-hover , стандартом де-факто.
Вот свежий скриншот с CanIUse. Если сравнить его с вышеприведённым, то окажется, что ситуация значительно улучшилась.
Поддержка pointer, any-pointer, hover и any-hover в 2021 году
Я полагаю, что мы можем приступить к серьёзному использованию этих медиазапросов, даже несмотря на то, что стандарт, в котором они описаны, всё ещё пребывает в статусе черновика. Их браузерная поддержка достаточно широка, что позволяет пользоваться ими, не особенно сильно беспокоясь о том, какой именно браузер применяют пользователи некоего веб-проекта (и, пожалуйста, забудем об Internet Explorer).
Пользуетесь ли вы медиазапросами, в которых применяются свойства pointer, any-pointer, hover и any-hover?
Свойство hover
Мультимедийная функция hover используется для выполнения запроса, направленного на выяснение возможности пользователя наводить указатель основного указывающего устройства на элементы. Если у устройства имеется несколько указывающих устройств, то hover-запрос должен отражать характеристики «основного» указывающего устройства, определённого пользовательским агентом.
В стандарте упоминается «основное указывающее устройство», что говорит о том, что соответствующий медиазапрос возвратит сведения именно о том механизме, который является основным при вводе информации на некоем устройстве (это может быть, например, некий метод ввода, жест, или физическое устройство ввода).
Соответствующий стандарт W3C пока имеет статус черновика, но уже сейчас можно говорить о том, что свойство hover может принимать два значения — hover и none , которые можно использовать в медиазапросах.
Если при использовании основного механизма ввода можно без труда навести указатель на элемент — на него отреагирует медиазапрос, в котором применяется значение hover :
Если основной механизм ввода не позволяет навести указатель на элемент, или позволяет, но это не очень-то просто (например — для имитации наведения указателя на элемент используется длительное касание экрана), или если у устройства нет основного указывающего устройства — сработает запрос, в котором применяется значение none :
Ориентация устройства
Ориентация | JavaScript Метод |
---|---|
Landscape | device.landscape() |
Portrait | device.portrait() |
60 Answers 60
Editor's note: user agent detection is not a recommended technique for modern web apps. See the comments below this answer for confirmation of this fact. It is suggested to use one of the other answers using feature detection and/or media queries.
Instead of using jQuery you can use simple JavaScript to detect it:
Or you can combine them both to make it more accessible through jQuery.
Now $.browser will return "device" for all above devices
Note: $.browser removed on jQuery v1.9.1. But you can use this by using jQuery migration plugin Code
A more thorough version:
For me small is beautiful so I'm using this technique:
In jQuery/JavaScript file:
My objective was to have my site "mobile-friendly". So I use CSS Media Queries do show/hide elements depending on the screen size.
For example, in my mobile version I don't want to activate the Facebook Like Box, because it loads all those profile images and stuff. And that's not good for mobile visitors. So, besides hiding the container element, I also do this inside the jQuery code block (above):
I'm still working on the the mobile version, so it's still not looking as it should, as of writing this.
Update by dekin88
There is a JavaScript API built-in for detecting media. Rather than using the above solution simply use the following:
The advantage of this method is that it's not only simpler and shorter, but you can conditionally target different devices such as smartphones and tablets separately if necessary without having to add any dummy elements into the DOM.
-1 The screen.width property is a global. There's no need to arbitrarily add an element to the DOM and unnecessarily bring in CSS media queries. Plus, if the browser is on a desktop and the user resizes the window, $is_mobile is not going to be updated.
The bootstrap/jquery technique is very good if it's put in a function. Just call on screenorientation changed or when size change.
In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.
This will match all common mobile browser user agents, including mobile Mozilla, Safari, IE, Opera, Chrome, etc.
Update for Android
EricL recommends testing for Android as a user agent also, as the Chrome user agent string for tablets does not include "Mobi" (the phone versions do however):
The linked article mentions: If the device is large enough that it's not marked with “Mobi”, you should serve your desktop site (which, as a best practice, should support touch input anyway, as more desktop machines are appearing with touchscreens).
A simple and effective one-liner:
However above code doesn't take into account the case for laptops with touchscreen. Thus, I provide this second version, based on @Julian solution:
It provides scripts to detect mobile browsers in several languages, one of which is JavaScript. That may help you with what you're looking for.
Since I don't know what exactly what you're trying to accomplish, I don't know which of these will be the most useful.
All that being said, I think your best bet is to either redirect or write a different script to the output using a server-side language (if that is an option). Since you don't really know the capabilities of a mobile browser x, doing the detection, and alteration logic on the server side would be the most reliable method. Of course, all of that is a moot point if you can't use a server side language :)
I have been asked to create an actual HTML page / JavaScript to simulate detection of the mobile devices (iPhone / iPad / Android) using JavaScript code. This will then take the user to a different screen which asks them for their email address.
Медиазапросы, реагирующие на все типы устройств
Для того чтобы создавать медиазапросы, реагирующие на все типы устройств, можно пользоваться свойствами any-hover и any-pointer. Снова обратимся к документации:
Any-pointer используется для выполнения запроса на предмет наличия и точности указывающих устройств. Соответствующий запрос не принимает во внимание дополнительные устройства ввода, не являющиеся указывающими, и не может быть использован для проверки наличия других механизмов ввода данных, таких, как d-пады, или средства управления, основанные лишь на клавиатуре, которые не позволяют перемещать экранный указатель. Запрос «any-pointer: none» вернёт true только в том случае, если на исследуемом устройстве нет ни одного указывающего устройства.
Запрос « any-hover: none » вернёт true в том случае, если указывающего устройства нет, или если все имеющиеся указывающие устройства не позволяют навести указатель на элемент. В силу этого подобные запросы следует рассматривать как способ проверки наличия хотя бы одного указывающего устройства, позволяющего наводить указатель на элементы, а не проверки того, что какое-то из указывающих устройств не позволяет наводить указатель на элементы. Последняя задача в текущих условиях не может быть решена ни с помощью медиазапроса any-hover, ни с помощью какого-то другого медиазапроса, направленного на анализ возможностей по взаимодействию пользователя с устройством. Кроме того, any-hover-запросы не принимают во внимание наличие на устройстве механизмов ввода данных, не относящихся к указывающим устройствам, таких, как d-пады и клавиатуры, которые, по своей природе, не позволяют наводить указатели на элементы.
Определение устройства
Устройство | JavaScript Метод |
---|---|
Mobile | device.mobile() |
Tablet | device.tablet() |
iOS | device.ios() |
iPad | device.ipad() |
iPhone | device.iphone() |
iPod | device.ipod() |
Android | device.android() |
Android Phone | device.androidPhone() |
Android Tablet | device.androidTablet() |
BlackBerry | device.blackberry() |
BlackBerry Phone | device.blackberryPhone() |
BlackBerry Tablet | device.blackberryTablet() |
Windows | device.windows() |
Windows Phone | device.windowsPhone() |
Windows Tablet | device.windowsTablet() |
Firefox OS | device.fxos() |
Firefox OS Phone | device.fxosPhone() |
Firefox OS Tablet | device.fxosTablet() |
Node.js / Express:
Итоги
Помните о том, что использовать эти возможности стоит лишь в том случае, если вы уверены в том, что с вашей системой будут работать, используя браузеры, поддерживающие соответствующие медиазапросы.
К несчастью, в момент написания этого материала рассматриваемый стандарт имел лишь статус черновика. Поэтому пока нельзя говорить о широкой поддержке рассматриваемых возможностей, что можно видеть на следующем рисунке.
Поддержка pointer, any-pointer, hover и any-hover в 2018 году
Хочется надеяться, что эти возможности войдут в официальный стандарт CSS 4.
А пока, чтобы получить кросс-браузерное решение, работоспособное на самых разных устройствах, можно обратиться к соответствующим JavaScript-проектам вроде этого.
Примеры медиазапросов, ориентированных на конкретные устройства
Два вышеописанных свойства можно комбинировать, что позволяет строить медиазапросы, реагирующие на существующие устройства разных типов:
Обратите внимание на то, что если имеется несколько указывающих устройств, hover- и pointer-запросы возвращают сведения об основном указывающем устройстве.
Использование
Подключаем скрипт и работаем дальше:
5 последних уроков рубрики "jQuery"
Анимация набора текста на jQuery
Сегодня мы бы хотели вам рассказать о библиотеке TypeIt — бесплатном jQuery плагине. С её помощью можно имитировать набор текста. Если всё настроить правильно, то можно добиться очень реалистичного эффекта.
Временная шкала на jQuery
jQuery плагин для создания временной шкалы.
Заметка: Перезагрузка и редирект на JavaScript
Быстрая заметка, где вы сможете найти парочку JS сниппетов для перезагрузки и перенаправления пользователей через JavaScript.
У разработчиков, которым нужно выявлять устройства с сенсорными экранами, пользуясь исключительно CSS, появилась, благодаря новым возможностям CSS, надежда на светлое будущее. Речь идёт о черновике стандарта CSS Media Queries Level 4, в котором описаны два новых свойства — hover и pointer.
21 Answers 21
I know this answer is coming 3 years late but none of the other answers are indeed 100% correct. If you would like to detect if the user is on ANY form of mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), then you can use the following code:
You would detect the requesting browsers user agent string, and then decide based on what it is if it's coming from a mobile browser or not. This device is not perfect, and never will be due to the fact that user agents aren't standardized for mobile devices (at least not to my knowledge).
Example:
You could get the user agent in javascript by doing this:
And then do the check's in the same format as this (just using iPhone as a quick example, but others would need to be a little bit different)
Edit
You'd create a simple HTML page like so:
But I am wondering what would be start? Create a dummy webpage and embedd this coding in there. Is it html that we will use in, because as I mentioned in my code above, I have nothing to start with.
Great. Thanks for that. How about redirecting it to a different page. Do you think something like this would help? if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/Android/i))) < if (document.cookie.indexOf("iphone_redirect=false") == -1) window.location = "m.espn.go.com/wireless/?iphone&i=COMR";
A pretty simple solution is to check for the screen width. Since almost all mobile devices have a max screen width of 480px (at present), it's pretty reliable:
The user-agent string is also a place to look. However, the former solution is still better since even if some freaking device does not respond correctly for the user-agent, the screen width doesn't lie.
The only exception here are tablet pc's like the ipad. Those devices have a higher screen width than smartphones and I would probably go with the user-agent-string for those.
Right!! I only need to detect iPhone or Android. So this shouldn't be a problem, but just to let you know I have absolutely nothing to start with. Shall I create a dummy Webpage and embedd this! Also how would the detection be checked? Would I need to transfer the script to a phone?
Even though this code won't execute more than one block since it's checking one thing over and over again, this code should make use of else-if blocks because of that reason. Also, what if the user agent variable changes somehow in between blocks? It'll execute more than 1 block, here.
You are right ,and don't forget that code was 4 years ago :) and there is now better tools or ways to do the same job
+1 for regex matching allowing users to easily check for multiple devices in one shot. However, I would add for clarity that because you denote /i at the end of the regex for insensitive match there really is no need to camel case the search params. The following would be equivalent (and also search for android devices): .match(/ipad|iphone|ipod|android/i)
A simple solution could be css-only. You can set styles in your stylesheet, and then adjust them on the bottom of it. Modern smartphones act like they are just 480px wide, while they are actually a lot more. The code to detect a smaller screen in css is
Hope this helps!
So I did this. Thank you all!
Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):
Note from MDN Note: CSS2.1 and Media Queries 3 defined several additional media types (tty, tv, projection, handheld, braille, embossed, aural), but they were deprecated in Media Queries 4 and shouldn't be used.
You can use the user-agent string to detect this.
In a nutshell, if you import a tiny JS file:
you will be left with a JSON object that looks like:
(that's assuming you are using a Nexus 7, of course) and you will be able to do things like:
This is what you are looking for.
Disclaimer: I work for the company that offers this free service. Thanks.
This is an example of how to check if webpage is loaded in Desktop or mobile app.
JS will execute on page load and you can do Desktop specific things on page load eg hide barcode scanner.
Determine what the User Agent is for the devices that you need to simulate and then test a variable against that.
Device detection based on user-agent is not very good solution, better is to detect features like touch device (in new jQuery they remove $.browser and use $.support instead).
To detect mobile you can check for touch events:
Down vote because OP is asking for mobile device. With touchscreen laptops nowadays, 'Touch Device' is not a very good solution.
Oh boy, I've had some laptops that are pretty useless at being portable! 🙃 But either way, OP gave iPhone, iPad, and Android as examples for what they wanted to detect, and "mobile" is short for "mobile phone". Probably a better description would've been "keyboardless"
The cleanest way of finding device type is:
(although it isn't yet supported on Safari)
This is my version, quite similar to the upper one, but I think good for reference.
Another possibility is to use mobile-detect.js. Try the demo.
Свойство pointer
Мультимедийная функция pointer используется для выполнения запроса на предмет наличия и точности указывающего устройства, такого, как мышь. Если имеется несколько указывающих устройств — сведения, возвращаемые запросом pointer, должны отражать характеристики «основного» указывающего устройства, определённого пользовательским агентом.
Тут, опять же, идёт речь об «основном указывающем устройстве».
Свойство pointer может иметь одно из трёх значений — coarse , fine и none .
Если основной механизм ввода данных включает в себя указывающее устройство ограниченной точности — используется значение coarse :
Если основной механизм ввода данных включает в себя точное указывающее устройство — используется значение fine :
Если же в состав основного механизма ввода данных указывающее устройство не входит — применяется значение none :
Example:
As I (kind of without success) searched for the proper solution for my hack, I want to add my hack here nonetheless: I simply check for support of device orientation, which seems the most significant diffrence between mobiles and desktop:
var is_handheld=0; // just a global if(window.DeviceOrientationEvent)
That being said, imho a page should also offer manual choice between mobile / desktop layout. I got 1920*1080 and I can zoom in - an oversimplified and feature-reduced wordpressoid chunk is not always a good thing. Especially forcing a layout based on nonworking device detection - it happens all the time.
Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:
That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.
The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.
In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.
В веб разработке все чаще приходится учитывать мобильные устройства, чтобы подстроить CSS и javascript-ы под нужды пользователей. Рассмотрим отличный скрипт device.js, который позволяет менять CSS и поведение всего сайта в зависимости от того устройства, через которое мы на него зашли.
Данный скрипт совершенно бесплатен и его стали использовать многие разработчики в современных проектах. Он имеет очень маленький вес - всего 8кб и совершенно не нагружает сайт. Разберем более подробно возможности device.js.
Данный скрипт может:
1. Определить тип устройства (ПК, телефон или планшет).
2. Узнать ориентацию экрана: горизонтальная (альбомная) или вертикальная (портретная).
3. Определить тип Операционной системы устройства (iphone, android, windows, iOS и т.д.)
Причем данные функции можно комбинировать, например, мы можем сначала определить, с какого устройства зашел пользователь - если с планшета - грузим такой-то CSS или выполняем действия для планшета, если с ПК - то грузим другой CSS, затем мы может определить тип ориентации экрана и в зависимости от него, так же выполнять свой действия.
Теперь о том, какие команды надо использовать для работы со скриптом:
В данном примере эти проверки делают сканирование на тип устройства, его ОС и ориентацию экрана. Результаты проверки вы увидите в виде алертов.
Device.js позволяет осуществлять проверки типа устройства (iOS, Android, Blackberry, Windows, Firefox OS), а так же его ориентацию (книжная или альбомная), и тип (планшет или мобильный телефон).
- iOS: iPhone, iPod, iPad
- Android: Телефоны & Планшеты
- Blackberry: Телефоны & Планшеты
- Windows: Телефоны & Планшеты
- Firefox OS: Телефоны & Планшеты
Читайте также: