Change URL based on display width - javascript

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

Related

Jquery window.resize(event) => {} works for inspect element but not when the chrome (or edge) window is resized

There are many many questions regarding resize (event) not working online, but I was only able to find one that actually reflected my exact problem but did not have an answer.
When I use inspector, my website changes from the desktop version to the mobile version when it reaches the breakpoint of <= 540px width. However, when I resize the entire chrome window, nothing happens (even though my window does get smaller than 540px width).
I'm not sure if the mobile version will actually work on a mobile as I have no way of testing that currently, but I'm unsure as to whether this is a normal thing with Chrome and the website will work perfectly well on desktop and mobile or whether I'm doing something wrong.
The related piece of code:
$(window).resize((event) => {
const windowWidth = window.screen.width;
if (windowWidth <= 540) {
$('.className1').addClass('d-none');
$('.classname2').css("width", "100%");
$('.classname3').css("left", "3%");
$('.classname3').css("width", "100%");
$('.classname4').css("width", "90%");
This is not the entire method but it basically shows the idea that css and attributes change based on window width dropping below 540px.
What I tried:
Document.resize (failed)
I really hope this isn't a duplicate, it's hard to navigate the vast number of questions out there.
The problem is not with the resize event or with browser. It's occurring because you're using window.screen.width, which is relative to the screen, not to the browser window. It doesn't matter if you resize the browser window, the screen width will not change. For example, if your screen has resolution of 1900x1200, screen.width will always be 1900. Hence, you should use window.innerWidth, or just innerWidth to get the viewport width. To know more, see this question.
Your code would be that way:
(window).resize((event) => {
if (innerWidth <= 540) {
$('.className1').addClass('d-none');
$('.classname2').css("width", "100%");
$('.classname3').css("left", "3%");
$('.classname3').css("width", "100%");
$('.classname4').css("width", "90%");
An example of working code (open the snippet in full page and resize it):
$(window).resize((event) => {
if (innerWidth <= 540) {
document.write('It\'s working.');
}
});
<html>
<body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>

How do you use javascript to detect if a user has multiple monitors?

Is it possible to use javascript to detect if a user has multiple monitors? And additionally if the monitors are "cloned" or in "extended desktop" mode?
You can check if a screen is extended.
window.screen.isExtended
The only place I can find info on it is here. I think it is still a draft spec.
Support (17/05/22):
✅ Chrome (v101)
⛔️ Firefox (v100)
⛔️ Safari (v15.4)
I'm pretty sure it's impossible to find that out but you can make an educated guess using the following (untested) code:
var dual_monitor = ( (screen.width / screen.height) > 2 )
This will test if the (total) monitor width is at least twice as wide as the height, the closest (normal) ratio is 16:9, even this would return false, so If dual_monitor == true, it is fairly safe to say that the user has two monitors.
P.S This will only cover situations where the use has side-by-side, non-cloned displays.

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

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.

jQuery/JS, iOS 4 and $(document).height() problems

I've run into an odd issue with what appears to be various versions of Webkit browsers. I'm trying to position an element on the center of the screen and to do the calculations, I need to get various dimensions, specifically the height of the body and the height of the screen. In jQuery I've been using:
var bodyHeight = $('body').height();
var screenHeight = $(window).height();
My page is typically much taller than the actual viewport, so when I 'alert' those variables, bodyHeight should end up being large, while screenHeight should remain constant (height of the browser viewport).
This is true in
- Firefox
- Chrome 15 (whoa! When did Chrome get to version 15?)
- Safari on iOS5
This is NOT working in:
- Safari on iOS4
- Safari 5.0.4
On the latter two, $(window).height(); always returns the same value as $('body').height()
Thinking it was perhaps a jQuery issue, I swapped out the window height for window.outerHeight but that, too, does the same thing, making me think this is actually some sort of webkit problem.
Has anyone ran into this and know of a way around this issue?
To complicate things, I can't seem to replicate this in isolation. For instance: http://jsbin.com/omogap/3 works fine.
I've determined it's not a CSS issue, so perhaps there's other JS wreaking havoc on this particular browser I need to find.
I've been fighting with this for a very long time (because of bug of my plugin) and I've found the way how to get proper height of window in Mobile Safari.
It works correctly no matter what zoom level is without subtracting height of screen with predefined height of status bars (which might change in future). And it works with iOS6 fullscreen mode.
Some tests (on iPhone with screen size 320x480, in landscape mode):
// Returns height of the screen including all toolbars
// Requires detection of orientation. (320px for our test)
window.orientation === 0 ? screen.height : screen.width
// Returns height of the visible area
// It decreases if you zoom in
window.innerHeight
// Returns height of screen minus all toolbars
// The problem is that it always subtracts it with height of the browser bar, no matter if it present or not
// In fullscreen mode it always returns 320px.
// Doesn't change when zoom level is changed.
document.documentElement.clientHeight
Here is how height is detected:
var getIOSWindowHeight = function() {
// Get zoom level of mobile Safari
// Note, that such zoom detection might not work correctly in other browsers
// We use width, instead of height, because there are no vertical toolbars :)
var zoomLevel = document.documentElement.clientWidth / window.innerWidth;
// window.innerHeight returns height of the visible area.
// We multiply it by zoom and get out real height.
return window.innerHeight * zoomLevel;
};
// You can also get height of the toolbars that are currently displayed
var getHeightOfIOSToolbars = function() {
var tH = (window.orientation === 0 ? screen.height : screen.width) - getIOSWindowHeight();
return tH > 1 ? tH : 0;
};
Such technique has only one con: it's not pixel perfect when page is zoomed in (because window.innerHeight always returns rounded value). It also returns incorrect value when you zoom in near top bar.
One year passed since you asked this question, but anyway hope this helps! :)
I had a similar problem. It had to do with 2 thing:
Box-sizing CSS3 property:
In the .height() jQuery documentation I found this:
Note that .height() will always return the content height, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS height plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "height" ) rather than .height().
This may apply to $('body').height().
Document ready vs Window.load
$(document).ready() is run when the DOM is ready for JS but it's possible that images haven't finished loading yet. Using $(window).load() fixed my problem. Read more.
I hope this helps.
It is 2015, we are at iOS 8 now. iOS 9 is already around the corner. And the issue is still with us. Sigh.
I have implemented a cross-browser solution for the window size in jQuery.documentSize. It stays clear of any kind of browser sniffing and has been heavily unit-tested. Here's how it works:
Call $.windowHeight() for the height of the visual viewport. That is the height of the area you actually see in the viewport at the current zoom level, in CSS pixels.
Call $.windowHeight( { viewport: "layout" } ) for the height of the layout viewport. That is the height which the visible area would have at 1:1 zoom - the "original window height".
Just pick the appropriate viewport for your task, and you are done.
Behind the scenes, the calculation roughly follows the procedure outlined in the answer by #DmitrySemenov. I have written about the steps involved elsewhere on SO. Check it out if you are interested, or have a look at the source code.
Try this :
var screenHeight = (typeof window.outerHeight != 'undefined')?Math.max(window.outerHeight, $(window).height()):$(window).height()
A cross browser solution is set that by jQuery
Use this property:
$(window).height()
This return a int value that represents the size of visible screen height of browser in pixels.

Getting the window size of the opener window (IE)

For FF and other non-IE browsers, window.opener.outerWidth/Height give me the info I need. For IE, I'm still at a loss, from IE6 to 8. I can't use jquery as the opener's page is beyond my control, so I can't do a window.opener.$(window). This requires the opener to have jquery 'attached' (correct me if I'm wrong).
I googled quite a bit and also searched this site, still can't find a definite neat answer.
To add:
I really need the outer size so that I can do a resizeTo(w, h) for the opened window where w and h are calculated based on a ratio of the opener's size. "resizeTo" ironically sets the outer size for IE and other browsers. I also tried a messy loads of stuff using resizeBy, not good enough.
outerWidth and outerHeight define dimensions of the browser window (including sidebar, window chrome and window [re-]sizing borders/handles). Unfortunately you cannot get these dimensions in IE - only the window viewport dimensions are available (good enough for most applications I've seen). Aka window.innerWidth/window.innerHeight.
jQuery can give you the dimensions of the current window viewport, but not other windows (eg, openers, children, etc). So you'll have to code this yourself. Here is a crude sample:
// get viewport size (without scrolling) of the given window object
function clientSize(win) {
var width, height;
if(win.innerWidth || win.innerHeight) {
width = win.innerWidth;
height = win.innerHeight;
} else {
var doc = win.document;
width = doc.documentElement.clientWidth || doc.body.clientWidth;
height = doc.documentElement.clientHeight || doc.body.clientHeight;
}
return { width:width, height:height }
}
Try it like:
var openerSize = clientSize(window.opener);
// now use openerSize.width, openerSize.height
Also note that you can't read any of these values if the given window has loaded a document from another domain (security measure).

Categories