$(window).width() not working in IE9 [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
$(window).width() not working in IE9
I'm trying to do some DOM manipulation for responsive web design. In IE this is not working.
var w = $(document).width();
if (w > 940) {
console.log("If test");
} else {
console.log("Else test");
If I use window.width, it works in IE but stop working in other browsers. Is there a cross browser way for that?

var maskWidth = window.innerWidth;
var maskHeight = window.innerHeight;
As per, $(window).width() not working in IE9

Responsive designs should be done in CSS with media queries:
#media all and (max-width:940px) {
/* some style rules that should be put in place
if the window is smaller than 940px wide */
}

There is an inherent problem with your approach, and that is that "responsive" refers to the design responding to a change in size. With what you are doing here, you only get a detection when the browser loads.
Say, for example, you are using an iPhone to view this site and you turn the phone 45 degrees to landscape instead of portrait. Essentially, your width just changed but your width() didn't.
There are a couple of options I would recommend looking at if you need to use javascript for your DOM manipulation and can't accomplish it with pure CSS (which is generally the best way to go):
Check out the proposed matchMedia() method by Rob Tarr http://seesparkbox.com/foundry/responsive_web_design_and_javascript
Use http://modernizr.com/ or some other library that has already solved this problem for you.

Related

Turn off JavaScript when screen is a set size

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;

Change URL based on display width

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

Detecting a retina display iPad with javascript

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

How can I hide some ID elements using Javascript if the browser window is less than a given size?

I have been looking for an answer to this problem for hours and can't find anything that works.
I need to make some elements if a web page not visible if the browser window width is less than a given size. This is because there are some fixed position "buttons" on the left side of the window which expand when rolled-over, BUT if the window is less than about 1056 pixels in width, the buttons overlap the main page contents.
I have a script for returning the window size and putting that value into a variable.
I have got it to show a message if the variable value is less than 1056. (for testing)
I have seen ways how to make things visible or not with jQuery and and with Javascript but none of them work for me.
The id of the image I'm trying to hide is #go2.
here is a part of the script I have been trying to get to work:
if (viewportwidth <1056)document.write('<p>Your viewport width is LESS than 1056</p>');
if (viewportwidth <1056)document.getElementById('go2').style.display = 'none';
I have had to use {literal} tags as the pages are using SMARTY templates!
I am very new to javascript and jQuery and wouold appreciate any help.
Thanks.
To make sure that the behavior happens when the user resizes the window, you can also bind to the resize event:
jQuery(window).resize(function() {
if(jQuery(window).width() < 1056) {
jQuery(".hide-these").hide();
}
});
You can do, with jQuery:
if(viewportwidth <1056) {
$('.target').hide();
}
Also, you can hide the elements with CSS3, like so:
#media only screen and (min-width: 1056px) {
#go2 {
display:none;
}
}
CSS3 media queries do what you want without Javascript, however browser support is pretty patchy:
http://www.w3.org/TR/css3-mediaqueries/
Alternatively, you could use Javascript as you've suggested above, with the usual caveats about JS being turned on etc. JQuery makes it easier, if you like Javascript libraries:
http://www.ilovecolors.com.ar/detect-screen-size-css-style/
If not, there are plenty of tutorials you can Google that explain how to query window size with Javascript.

Anyone know how to calculate the DOCUMENT dimensions, NOT the VIEWPORT in Javascript?

Just to make sure everyone understands what I am asking for, I will run through what I believe are the basic distinctions between document, window, and viewport....
WINDOW is the entire browser window, including all nav bars, etc....
VIEWPORT is the portion of the window used to view the current XHTML/HTML/Flash document...
DOCUMENT is the actual content area, akin to the body but includes ALL of the page's content. Only a portion of it is visible at any one time in the VIEWPORT (unless the page is the same size or smaller than the viewport).
Now, there are many great answers for how to get the VIEWPORT dimensions. I am already well versed in that... cross-browser and all.
What I really need to know is a simple, cross-browser solution that will give me the dimensions of the actual DOCUMENT in all browsers (no versions older than 3 years).
I thought I found a great solution here once... long ago... but now I cannot find it.
Anyone? Thanks for the read and hopefully someone can help.
P.S. Did I mention I DO NOT want solutions for calculating the VIEWPORT? OR THE WINDOW?
UPDATE: this solution MUST work in Opera 10.x, FireFox 3.6.x, IE 7/8/x, Flock 2.x, Safari 4.x... None of the answers below work in all browsers....
So, if you have not tested it in all, please do not respond to the question.
document.body.scrollHeight and document.body.scrollWidth.
Should give it to you.
I stole this from jQuery's source and made a wrapper around it:
EDIT: Refactored the function so it returns both width and height in an array.
function getDocumentDimensions() {
var d = document;
return [
Math.max(
d.documentElement['clientHeight'],
d.body['scrollHeight'],
d.body['offsetHeight']
),
Math.max(
d.documentElement['clientWidth'],
d.body['scrollWidth'],
d.body['offsetWidth']
)
]
};
getDocumentDimensions() // [1284, 1265]
the jQuery for this would be $(document).height() and width.
I think if you wrap your entire contents into a DIV element with zero borders, padding and margins, then when the browser is finished rendering you can use jQuery's .height() method to interrogate the wrapping DIV for its actual height.
I have done this before, and I found I had specific problems with various browsers. You may not run into those problems that I had, but I ended up settling on this solution.
Sorry, but none of these answers were what I was looking for. In the end, I decided to just stick with document.body.getWidth() and document.body.getHeight() in Prototype.
We have a similar need and use this code. It's not tested in opera/flock, but we cover all the other browsers. Note that it's not always quite perfect, but does the job in 99%+ of the cases.
function getContentWidthHeight() {
var pageWidth = 0;
var pageHeight = 0;
if (window.innerHeight && window.scrollMaxY) {
pageWidth = window.innerWidth + window.scrollMaxX;
pageHeight = window.innerHeight + window.scrollMaxY;
}
if (document.body.scrollHeight) {
pageWidth = Math.max(pageWidth, document.body.scrollWidth);
pageHeight = Math.max(pageHeight, document.body.scrollHeight);
}
if (document.body.offsetHeight) {
pageWidth = Math.max(pageWidth, document.body.offsetWidth);
pageHeight = Math.max(pageHeight, document.body.offsetHeight);
}
if (document.documentElement.offsetHeight) {
pageWidth = Math.max(pageWidth, document.documentElement.offsetWidth);
pageHeight = Math.max(pageHeight, document.documentElement.offsetHeight);
}
if (document.documentElement.scrollHeight) {
pageWidth = Math.max(pageWidth, document.documentElement.scrollWidth);
pageHeight = Math.max(pageHeight, document.documentElement.scrollHeight);
}
return [ pageWidth, pageHeight ];
};

Categories