JavaScript tablet detection - javascript

Requirement - Detect tablets using JavaScript
I'm not allowed to use any plugin or lib (jQuery is an exception) and want to keep code to minimum.
I have read many posts on this topic and came up with this solution (Checking screen resolution and touch):
var _w = Math.max($(window).width(), $(window).height());
var _h = Math.min($(window).width(), $(window).height());
var tabletView = (_w >= 1000 && _h >= 600);
var is_touch_device = 'ontouchstart' in document.documentElement;
if (tabletView && is_touch_device) {
alert('tablet');
}
else {
alert('Not a Tablet');
}​
Question: Is this code reliable enough? If not what's the better approach?

This will also see phones with larger screen resolutions as tablets.
Other than that, this code is reliable, and there isn't really anything you could do to detect the difference between a phone and tablet, without libraries, or manually parsing user-agents.

Related

CSS And HTML : Apple Phone Like 3D Floating Effect For Images

Actually I don't know how I should call It, but I have Seen that -(Actually I don't have A IPhone But I have Seen Right!) In some Apple Phones(Some Or All?) have a System Like When We rotate the phone The Display Icons And Other staff are like to be floating Moving Slightly Here And There.
It's Cool For Me if I can use it in my website. I need to know How Can I make Such A HTML img Using CSS,HTML and with or without JAVASCRIPT or JQUERY. But Instead of Rotating A Phone(Of course no Phone) I need It to be done with the Mouse Pointer. Sample Code or Link for a Code Will Be Useful.
If there Is Already A answered Question Like this, Please Mark this as duplicate (with pleasure) :)
It sounds like you gotta go with Progressive Web App which will allow you to use native features - in this case getting movement of user's phone. This way you'll be able to apply 3D Transforms to DOM elements based on device movement/rotation.
If you want to stick with a cursor as an animation input, there are plenty of libraries and ready examples showing exactly how to do it.
Also, it's already been very well known topic on StackOverflow so you just gotta search a little to find your perfect solution.
StackOverflow: https://stackoverflow.com/a/35016817/8923822
CodePen by Thomas Podgrodzki: https://codepen.io/Podgro/pen/WQpEwY/
!(function ($doc, $win) {
var screenWidth = $win.screen.width / 2,
screenHeight = $win.screen.height / 2,
$elems = $doc.getElementsByClassName("elem"),
validPropertyPrefix = '',
otherProperty = 'perspective(1000px)',
elemStyle = $elems[0].style;
if(typeof elemStyle.webkitTransform == 'string') {
validPropertyPrefix = 'webkitTransform';
} else if (typeof elemStyle.MozTransform == 'string') {
validPropertyPrefix = 'MozTransform';
}
$doc.addEventListener('mousemove', function (e) {
var centroX = e.clientX - screenWidth,
centroY = screenHeight - (e.clientY + 13),
degX = centroX * 0.04,
degY = centroY * 0.02,
$elem
for (var i = 0; i < $elems.length; i++) {
$elem = $elems[i];
$elem.style[validPropertyPrefix] = otherProperty + 'rotateY('+ degX +'deg) rotateX('+ degY +'deg)';
};
});
})(document, window);
You can always make use of 3rd party libraries.
Animate.css
For your particular animation I believe Shake would be the appropriate one.
Go to their github page to get more information. I've used this almost in each of my websites to add animations. Hope it helps!

Can I put if condition in javascript to detect any running script

I want to develop chrome extension to put a check on the script say this website runs http://whatsmyscreenresolution.com/
e.g.
if (his_script==my_script)
then
block it or return "123".
I want to do something like this.Is it possible or can I even block websites to detect my screen resolution, font, etc other than disabling javascript at my end?
can I even block websites to detect my screen resolution
You could define a new window.screen object
(function (screen) {
function clone(e) {
var o = {}, k;
for (k in e) o[k] = e[k];
return o;
}
Object.defineProperty(window, 'screen', {get: function () {
var o = clone(screen);
o.availHeight = o.height = Math.random() * (o.height - 600) + 600;
o.availWidth = o.width = Math.random() * (o.width - 600) + 600;
return o;
}});
}(window.screen));
After this, trying to access screen or window.screen will give you randomised (but not entirely unreasonable for styling purposes) values
DEMO
Take a look at the chrome.webRequest api: https://developer.chrome.com/extensions/webRequest
Theoretically, you could do this with the onBeforeRequest listener.
It doesn't think it's possible. Tried setting window.screen and creating a var screen but no matter what is written to screen.width and screen.height it always returns the correct resolution. It doesn't seem spoofable at least from a javascript console. You might try a hidden frame with the desired screen resolution for privacy and when the page is loaded adjust the resolution to actual browser resolution and display the frame.

Detect device type with UI Automation

I am using ui-screen-shooter, which makes use of the UI Automation JavaScript API to take screenshots of apps. My app has a slightly different structure on iPad and iPhone, so I need to detect the device type in my shoot_the_screen.js script and run different code. I would like something equivalent to [[UIDevice currentDevice] userInterfaceIdiom] that I can use in JavaScript. Here is the best I have come up with. It works, but do you know of a cleaner, less device-dependent way to get the same information?
var target = UIATarget.localTarget();
var width = target.rect().size.width;
if (width == 1024 || width == 768)
{
// iPad
}
else
{
// iPhone
}
You can call model() on the target to get the information you need. That's exactly what I'm doing in the ui-screen-shooter itself.
var modelName = UIATarget.localTarget().model();
// This prints "iPhone" or "iPad" for device. "iPhone Simulator" and "iPad Simulator" for sim.
UIALogger.logMessage(modelName);

Responsive JavaScript: execute code only for small device width

I have some simple JavaScript (embedded in an event) that I want to fire only for small devices. Phones, etc...
Currently I'm doing
if ($(window).width() < 606) {
do_things();
}
But this feels clunky. Is there a way to only execute this for devices smaller than a certain breakpoint (aside from just setting an earlier variable)? Ideally something that works with my CSS breakpoints.
I'm using Bootstrap, so there may be an easy option that utilizes that.
As crude as your code might look to you, this is actually in a nutshell what a media query is. If you look at the source for responsive.js (JS lib that adds media query support to older browsers) it includes this function:
function getDeviceWidth() {
if (typeof (window.innerWidth) == 'number') {
//Non-IE
return window.innerWidth;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
return document.documentElement.clientWidth;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
//IE 4 compatible
return document.body.clientWidth;
}
return 0;
}
While this is a more complete approach to detecting device width (and this is combined with an onResize event handler to detect things like rotation), it is fundamentally what you are doing.

Is it possible to detect a battery operated device in javascript?

A client recently asked me to implement a slideshow on our website. I'm concerned that constantly animating picture transitions on the homepage will peg the processor of most mobile devices, so I want to disable the automatic advancing to preserve battery life. Is there any way to do this without trying to detect the user agent?
I've seen that there is a battery status API drafted here, but I don't know how complete it is, or which browsers have implemented it.
Actually determining battery would be quite difficult and probably involve various permissions problems.
Try just executing a small piece of code and checking the time it took. Pick a cutoff and if the code executes too slowly, turn off the transitions/animation/autoadvance. This will catch more than just battery devices; anything too slow will get the un-animated version. Degrade gracefully.
Now you can, with this API: http://davidwalsh.name/javascript-battery-api
navigator.getBattery().then(function(result) {});
Another old topic, but still relevant - I now check if the device has motion sensors, not many laptops do, but all modern smart phones and tablets do - so laptop users can live with slightly more battery use -
jQuery:
if (window.DeviceOrientationEvent) {
$(window).one("devicemotion", function(event) {
if (event.originalEvent.acceleration
&& event.originalEvent.acceleration.x !== null) { // Chrome fakes it on desktop
isMobile = true;
}
});
}
Plain Javascript:
if (window.DeviceOrientationEvent) {
window.ondevicemotion = function(event) {
if (event.acceleration
&& event.acceleration.x !== null) { // Chrome fakes it on desktop
window.ondevicemotion = null;
isMobile = true;
}
};
}

Categories