MrBuggy MrBuggy - 4 months ago 25
jQuery Question

Check if it is tablet or desktop

Hi I've got follow code:



angular.module("myApp", []).controller("myController", function($scope) {
$scope.isShown = false;

$scope.togglePopup = function() {
$scope.isShown = !$scope.isShown;
}
});

.wrapper {
display: flex;
flex-direction: column;
width: 100%;
background-color: grey;
}
.inputAddon {
display: flex;
flex-direction: row;
}
input {
width: 75px;
height: 19px;
}
.addon {
width: 25px;
height: 25px;
background-color: green;
}
.popup {
width: 200px;
height: 200px;
border: 1px solid red;
background-color: white;
position: absolute;
z-index: 1000;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myController" class="wrapper">
<div class="inputAddon">
<input type="number">
<div class="addon" ng-click="togglePopup()"></div>
</div>
<div class="popup" ng-if="isShown"></div>
</div>





There you can see an input with a addon-button on the right side, which is opening something like a popup with more actions in it. Now it should work like this:


  • Desktop: Click in input field = focus in input field and type value with keyboard. Click on addon-button (green one) = opens the popup.

  • Tablet: Addon-button (green one) hidden. Click in input = don't open the costume keyboard of the browser (for example the virtual keyboard in safari from ipad). It opens the popup like the addon-button (green one) on desktop.



So I need a way to detect, if there is a tablet or desktop. When it's a tablet, I had to add the property
readonly="true"
to the input. This would not open the costume keyboard on a tablet. Also a need to hide the addon-button and open the popup when I click in the input. On the desktop it should work like in the snippet.

I know how to add/remove
readonly
and how to hide/show adddon-button with Jquery, Javascrpt etc. But what't the best way to detect if it't tablet or desktop? I found some questions with
$.browse
but I read, that it's not supported anymore sinse Jquery 1.9.1? Or is there also a way to do this with angular?

Any ideas/informations about this?

Thanks.

Answer

You can use UAParser.js : https://faisalman.github.io/ua-parser-js/

var parser = new UAParser();
var result = parser.getResult();
//Possible 'device.type':
//console, mobile, tablet, smarttv, wearable, embedded
console.log(result.device.type); 

More documentation info: https://github.com/faisalman/ua-parser-js