How do I turn Javascript off when my page is viewed on mobiles?
I need a sort of media query that will disable all javascript on a page when viewed on a specific device.
So far I have this but do not know how to actually disable all javascript
if(screen.width < 480) {
// do any 480 width stuff here, or simply do nothing
return;
} else {
// do all your cool stuff here for larger screens
}
Thanks
You could use matchMedia.js (found at https://github.com/paulirish/matchMedia.js) and check if the screen is below a certain size.
Eg.
if (matchMedia('(max-width: 480px)')) {
// Run Code Here
}
You can check the
navigator.userAgent
property with Javascript. This will show the used browser and you can determine if its mobile or not.
Documentation:
userAgent Docs
You can do it also width the viewport width of your users browser in pure Javascript:
var w = document.documentElement.clientWidth;
Related
I'm wondering why there is a difference when using $(window).width() in the browser standard and device emulation mode.
When I used $(window).width() on the browser with the width of 1024px i got the value of 1007 in standard mode, but when used it on device emulation mode i got the exact 1024.
So whats the difference between the two and is there anyway to check the specific width that is exact on the normal window mode and device emulation mode?
What i'm using now is $(window).width() for the checking of the window size so is there anyway to check the actual size beside this one?
the difference is in the scrollbar of your browser. In latest version of all browsers (http://www.textfixer.com/tutorials/browser-scrollbar-width.php) the scrollbar width is 17px and if you add it to 1007 you get exactly 1024px.
The measure is correct as it refers to the area of the browser that is "available" for rendering content - returning the browser full width would be incorrect.
Try to check position like,
function checkPosition() {
if (window.matchMedia('(min-width: 1024px)').matches) {
//...
} else {
//...
}
}
Alternatively, you can use modernizr mq method like,
if (Modernizr.mq('(min-width: 1024px)')) {
//...
} else {
//...
}
I have a jquery funciton which sticks the navbar to the top of the webpage, but I only want this feature in desktop and tablet mode (not in phone mode). How do I de-activate this function?
$(document).scroll(function(){
var elem = $('.navbar');
if (!elem.attr('data-top')) {
if (elem.hasClass('navbar-fixed-top'))
return;
var offset = elem.offset()
elem.attr('data-top', offset.top);
}
if (elem.attr('data-top') <= $(this).scrollTop() )
elem.addClass('navbar-fixed-top');
else
elem.removeClass('navbar-fixed-top');
});
Use CSS media queries to manipulate the nav bar. Browser/OS detection shouldn't factor into styling, just resolution and media type.
What is the syntax for a CSS media query that applies to more than one property (AND operator)?
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries
Based on your question, it seems like the real concern here is saving screen real estate on a mobile device. So as most of the other users have pointed out, you can rely on using media queries here instead. In order to make sure the listener isn't even attached in case of small screens, you can use Modernizr.mq to test a media query and use the returned value:
if( Modernizr.mq('only screen and (min-height: 640px)') ) {
// Case specific code here, only executed if screen height is > 640px
}
This is assuming you're willing to add Modernizr or are already using it. If you don't have it already included and only plan on using this single test, you can download a custom build(2kB) from modernizr.com which only includes the media query test.
Check this out -- It maybe what you're looking for they're Open source mobile phone detection
http://detectmobilebrowsers.com/
I created a hobby site a few years ago that started as a convenient compact one-line-entry multi-search site. Later, I added various web tools, one-click radio stations, and other enhancements.
At first, I optimized for 1024x768 screens but tried to accommodate 800x600 screens. However, wide screen format is becoming dominant, so I decided it would be better to optimize things a bit by splitting the code, mostly, but not limited to, CSS changes, based on detecting a minimum 960 pixel width.
Screen widths less than 960 pixels wide redirect to a "mini.php" version.
The javascript code below selects the appropriate URL correctly if the web browser is already open. However, when initially opening a browser, the "mini" version is incorrectly selected regardless of the screen width. I tried delaying detection by using setTimeout() without effect.
var myWidth = 981
function vpWidth() {
return( myWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth );
}
vpWidth(); setTimeout(vpWidth,300);
if(myWidth<960) document.location.href="http://www.gooplusplus.com/mini.php";
Who can provide a solution that always works and not just when the browser is already open?
You're never actually setting myWidth. Also, I replaced your function with how jQuery gets the width internally.
function vpWidth() {
return Math.max(document.documentElement["clientWidth"], document.body["scrollWidth"], document.documentElement["scrollWidth"], document.body["offsetWidth"], document.documentElement["offsetWidth"]);
}
var myWidth = vpWidth();
if(myWidth<960) document.location.href="http://www.gooplusplus.com/mini.php";
Make your website responsive which will help you to cover more number of visitors to your size, as most of the people use their smartphone to browse websites nowdays.
http://alistapart.com/article/responsive-web-design
Further testing this width error upon browser startup showed that it seems limited to Chromium-based browsers where the target tab is not the active one. In such cases, Google Chrome took its window width results from the non-maximized window size even though the window was actually maximized.
Two detection steps were required on the way to a solution:
(1) is the browser Chromium-based? --> navigator.userAgent.indexOf("Chrome/")>0
(2) is the tab inactive? --> document.webkitVisibilityState == "hidden"
test URL: http://www.gooplusplus.com/chrome-bug.html
my working solution:
<script>
var myWidth = 981
var dde = document.documentElement;
var tabVisible = document.webkitVisibilityState;
if(!document.documentElement) dde = document.body; // fix for IE6 and earlier
myWidth = Math.max(dde.scrollWidth,dde.offsetWidth,dde.clientWidth);
if( ( navigator.userAgent.indexOf("Chrome/")<0 || tabVisible!="hidden" ) && myWidth < 960 )
document.location.href="http://www.gooplusplus.com/mini.php";
</script>
The above technique fixed the problem. Although the #theJoeBiz answer turned out to be irrelevant to the ultimate solution, his code was useful. I based my own new myWidth assignment code on his jQuery Math.max code, while noting that his code failed on my non-jQuery web page due to inclusion of pre-IE7 document.body variables (see fix in code above).
I'm having a problem detecting a retina iPad (and similar devices) using just screen.availWidth and window.devicePixelRatio. The problem is that iPhones and iPads give the number of dips for screen.availWidth whereas android devices seem to report the number of physical pixels so I can't reliably do screen.availWidth / window.devicePixelRatio to calculate if the screen is of a tablet size.
Is there some other DOM property I can use to help me?
edit - To sum up in a way which hopefully makes clear that the question isn't a duplicate
How can I tell if screen.availWidth reports a value that has already been adjusted to take account of window.devicePixelRatio
That should help
var retina = (window.retina || window.devicePixelRatio > 1);
UPDATE
Retina.isRetina = function(){
var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\
(min--moz-device-pixel-ratio: 1.5),\
(-o-min-device-pixel-ratio: 3/2),\
(min-resolution: 1.5dppx)";
if (root.devicePixelRatio > 1)
return true;
if (root.matchMedia && root.matchMedia(mediaQuery).matches)
return true;
return false;
};
I haven't tested this, but here's an approach I think might work. I'll do a jsbin for it when I get time.
Because all devices (to the best of my knowledge) adjust for devicePixelRatio before passing the value to CSS media queries we can (in slightly pseudo code)
measure window.devicePixelRatio and screen.availWidth
Write a style tag to the head which includes a media query something like the following
#my-test-el {
display: none;
visibility: visible;
}
#media screen and (min-device-width:screen.availWidth) {
#my-test-el {
visibility: hidden;
}
}
Append <div id="my-test-el"> to the page
Read off the style.visibility attribute. If it equals hidden then the css value is the same value as screen.availWidth => screen.availWidth has been preadjusted for dpr.
edit It works! http://jsbin.com/IzEYuCI/3/edit. I'll put together a modernizr plugin too
edit And here's the pull request to get it in Modernizr - https://github.com/Modernizr/Modernizr/pull/1139. please upvote if you'd find it useful
This Modernizr plugin may help : Modernizr Retina : HiDPI Test
Note: Requires Modernizr's Media Queries feature
I have two images "image-big.jpg" and "image-small.jpg" I want to via javascript detect if screen width <= 699 and change the SRC of my image with class="imageswap" from image-big.jpg to image-small.jpg.
So basically if they are on a portable device it will display the smaller image.
I am novice at best with javascsript and any help is gratefully appreciated!
Bind to the window onresize event:
window.onresize = function(event) {
if(window.innerWidth && window.innerWidth===699)
document.getElementById('myImg').src = 'newSource';
else if(document.body.offsetWidth && document.body.offsetWidth===669)
document.getElementById('myImg').src = 'newSource';
};
The else if is for IE < v.9
Its no in specs but screen works fine in all browsers.
if(screen.width <= 699){
// do you logic
}
1st approach: client-side. Set classname to html tag on dom ready after detection device type. Use css:
html.big .image-div {background-image:url('big.jpg')}
html.small .image-div {background-image:url('small.jpg')}
2nd approach: redirect. Use 2 different URLs and redirect for small size by detection User-Agent. It's better to use User-Agent (navigator object) than window/screen width
Usually I preffer redirects, because you have better code and page look when you can customize it for specific device. It's the way how leaders behave.
Try media-query.
.imageswap{
background-image:url('small.jpg');
}
#media screen and (max-width: 699px) {
background-image:url('small.jpg');
}