Responsive JavaScript: execute code only for small device width - javascript

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.

Related

Detecting NON-mobile devices with JavaScript

Before voting for duplicate:
Please read the full question below. I explained there why any of "how to detect mobile device?" is not a case here.
Question (and why it's not a simple negation of mobile dev. detection):
There are plenty of questions about "How to detect an mobile device with JavaScript?" (one of the best, if you are looking for it: What is the best way to detect a mobile device in jQuery?), but I want to ask for something a bit different: "How to detect non-mobile device with JavaScript?".
You might think that when I can make an mobile detection like this:
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile
|Opera Mini/i.test(navigator.userAgent)){
alert('mobile');
}
I can just put negation before the statement inside if and that would be check for non-mobile device. Not really.
The code above detects several versions of mobile devices. For all not recognized devices, we cannot be 100% sure that they are not mobile. If userAgent contains one of the typed literals (webOS, iPone etc.) it's surely a mobile device. If not, it can goes two ways:
It's not a mobile device
It's a mobile device that we did not listed (mistake, exotic device, device released after we wrote the code etc.)
So instead of negating the test for mobile device, I want to write a test for non-mobile (Linux/Windows PC, Mac etc.). That way, if the result will be true, I will be 100% sure that I deal with non-mobile device. In the other case - it's rather mobile, but it's only an strong assumption.
So basically, I want to react only when I'm 100% sure it's non-mobile device, and when I do not know it for sure, I don't want to take any steps (or I will assume it's a mobile device).
How would that formula look? It's safe to test against Windows (Windows Phone or something like that could also use that literal?)? What about Mac, Linux PC and others?
This is taken from here:
var BrowserDetect = function() {
var nav = window.navigator,
ua = window.navigator.userAgent.toLowerCase();
// detect browsers (only the ones that have some kind of quirk we need to work around)
if (ua.match(/ipad/i) !== null)
return "iPod";
if (ua.match(/iphone/i) !== null)
return "iPhone";
if (ua.match(/android/i) !== null)
return "Android";
if ((nav.appName.toLowerCase().indexOf("microsoft") != -1 || nav.appName.toLowerCase().match(/trident/gi) !== null))
return "IE";
if (ua.match(/chrome/gi) !== null)
return "Chrome";
if (ua.match(/firefox/gi) !== null)
return "Firefox";
if (ua.match(/webkit/gi) !== null)
return "Webkit";
if (ua.match(/gecko/gi) !== null)
return "Gecko";
if (ua.match(/opera/gi) !== null)
return "Opera";
//If any case miss we will return null
return null;
};
It's not very elegant but you can add/remove it to your preference.
A second answer, while I understand you are specifically looking for a NON mobile detection, you could also use http://detectmobilebrowsers.com/ which has almost complete mobile device detection (Even the less popular).

Magento Javascript Error - Diagnosing

my javascript megamenu dropdown is not working and the sidebanner too. I think its a javascript problem but I am trying hard to determine what actually goes wrong.
I used google chrome "Inspect Element" > Console and there are 3 issues:
TypeError: $.browser is undefined fixed: !$.browser.msie || $.browser.version > 6,
Use of getPreventDefault() is deprecated. Use defaultPrevented instead.
TypeError: $j.browser is undefined
var safari = $j.browser.safari; /* We need to check for safari to fix the input:...
I would appreciate if anybody can point me to the correct directions on what is wrong with the javascript? Thank you in advance.
You should use less Div(s) in your code.
Your Two Drop-Menus : Account and Shop by Categories aren't working.
As for the sidebar, I believe your have wrong box dimensions. Your Bullon chart is cut.
Some of your Menus are longer than the rest.
What makes you believe that there is an error in your page ?
You should use the inner variables provided by browser. I have seen many translate code.
Here is a sample code :
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
It was taken from HowtoCreate.co.uk
If you want to use drop menus, you need to use events like Click. W3C has many code samples and good documentation.
Here is a fun code sample from W3C School :
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>
You can always use JQuery if you want the easy or effective method. Javascript has many libraries that you can use.
See this page to find deprecated and obsolete functions in JQuery : http://api.jquery.com/category/deprecated/
You can find deprecated functions in Javascript in this page : "Mozilla Deprecated and Obsolete features"
If you want to continue using old functions, you can downgrade or make use of plug-ins to restore old features.

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);

Substitute for ALLOW_KEYBOARD_INPUT javascript full screen

I have been searching on the internet for a reason why my fullscreen javascript doesn't work in Safari, but yet works in webkit browser Chrome. It seems to that safari doesn't support the element.ALLOW_KEYBOARD_INPUT add-on for webkitRequestFullScreen.
function cancelFullScreen(el) {
var requestMethod = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullscreen;
if (requestMethod) { // cancel full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
function requestFullScreen(el) {
// Supports most browsers and their versions.
var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen(el.ALLOW_KEYBOARD_INPUT) || el.mozRequestFullScreen || el.msRequestFullScreen;
if (requestMethod) { // Native full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
return false
}
function toggleFull() {
var elem = document.body; // Make the body go full screen.
var isInFullScreen = (document.fullScreenElement && document.fullScreenElement !== null) || (document.mozFullScreen || document.webkitIsFullScreen);
if (isInFullScreen) {
cancelFullScreen(document);
} else {
requestFullScreen(elem);
}
return false;
}
Does anybody know a way to make safari accept fullscreen yet still be able to handle keyboard inputs?
According to Apple's documentation, this is supposed to work in Safari 5.1 and later, but obviously it doesn't. I filed a bug report with Apple (which they don't make public), and the reply was as follows:
Engineering has determined that this issue behaves as intended based on the following:
We intentionally disable keyboard access in full screen for security reasons.
I have replied asking that they at least update the documentation and make the lack of feature support detectable somehow. I will update here if I get a reply.
Unfortunately, there isn't a good way to even do feature detection, since element.ALLOW_KEYBOARD_INPUT is defined in Safari, and the function call with that flag doesn't throw an error. The only remaining option is to parse the user agent string (try this library).
Obviously, Apple doesn't yet document which version supports this, but according to this, it stopped working as of v5.1.2. That would leave a very small number of people using 5.1 un-patched, if it ever even worked at all. So it's probably not even worth detecting the version.
As a fallback, I would expand the desired DOM element to fill the browser window by setting CSS height and width to 100% and position to "fixed" or "absolute".
Update: It looks like the documentation has been corrected and no longer mentions the ALLOW_KEYBOARD_INPUT flag.
This has been fixed in Safari 10.1!
Under the "Safari Browser Behavior" section.

JavaScript tablet detection

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.

Categories