JavaScript getting the wrong window size - javascript

I am messing around with some code and applying / removing classes based on window size and I'm running into a weird error. I've confirmed that I'm at the default zoom (if that matters), and I've replicated the issue in FF & Chrome.
I have a resize event handler that I'm just using to monitor the javascript window width value vs. the actual value (I have a chrome extension which shows the window & viewport width as you're resizing, and my bootstrap viewports hit exactly as they should at 992px, 1200px etc, so I know that the javascripts value is off for some reason and not vice-versa)
For some reason, as I resize the window, the value for window width that shows in the console.log, is always 21px smaller than the actual screen size. This is the code that I'm using for the test:
var w = 0;
$(function () {
w = $(window).innerWidth() || $(window).width();
})
$(window).resize(function () {
if (w != $(window).innerWidth()) {
w = $(window).innerWidth() || $(window).width();
console.log(w);
}
});

Give this a try:
var iw = $('body').innerWidth();
jsBin demo
answer from: https://stackoverflow.com/a/8340177/504836

Related

How to get window width via Javascript

I am looking for some help concerning my Jquery. I have an animation, that is opening a navigation menu, running from the right window site into the middle. What I want to do now is: When the user is reducing the browser window width (lets say in a step of 100px), the Animation should run a 100px less into the middle. Below you can the the short version of my code. Is there a way to define the width using the value of a class, that I have written in my css?
$(".slide-left").click(function(){
$("#navibox").animate({ width: 863 }); });
You cannot define the width with the value in a class. Although to get the width of the window itself, you can use
window.innerWidth
If you'd like to have some code run when you resize you can add an eventListener, with the event name of 'resize' like this.
window.addEventListener('resize', (e)=>{})
The event passed from that callback has the property 'target' which is the window instance that you can grab the innerWidth from again.
If you have to update the animation with some new evaluated width, you can do it there.
Thanks! I already tried something like this:
$(window).resize(function(){
if ($(window).width() > 1000) { mywidth = 863; }
if ($(window).width() < 1001 && $(window).width() > 959 ) { mywidth = 823; }
if ($(window).width() < 960) { mywidth = 783; }
});```
In the animation I used:
```$("#navibox").animate({ mywidth });```
But that did not work...

Get Android Chrome Browser Address bar height in JS

How do I get the height of the address bar in JavaScript in the Chrome browser for Android (marked by red rectangle in left picture)? I need to know that as it disappears while scrolling down and I need to react to that because the viewport height is different then.
One solution I already figured out:
Get viewport height at initial state:
var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
Get viewport height when the address bar has disappeared
Compute difference between both values
Problem is that you have to be in the second state to know that.
Because 100vh will be larger than the visible height when the URL bar is shown. According to this.
You can calculate the height of the URL bar by creating a 0-width element with 100vh height.
<div id="control-height"></div>
#control-height {
height: 100vh;
width: 0;
position: absolute;
}
Then using javascript compare window.innerHeight with the height of this element.
const actualHeight = window.innerHeight;
const elementHeight = document.querySelector('#control-height').clientHeight;
const barHeight = elementHeight - actualHeight;
The thing you're are looking for is url bar resizing. Since Android's chrome v56, it's recommended by David Bokan to use vh unit on mobile. There is a demo in that article, clicks the link to get more informations and how to use it on mobile.
When the user is scrolling down the page, a window.resize event is throwed.
You could update your page by catching this event with an event listener.
More informations : mobile chrome fires resize event on scroll
Best approach for me was to have something like that:
$(document).ready(function(){
var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var isPortrait = viewportHeight > viewportWidth;
$( window ).resize(onresize);
function onresize() {
var newViewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var newViewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var hasOrientationChanged = (newViewportHeight > newViewportWidth) != isPortrait;
var addressbarHeight = 130;
if (!hasOrientationChanged && (newViewportHeight != viewportHeight)) {
addressbarHeight = Math.abs(newViewportHeight - viewportHeight);
if (newViewportHeight < viewportHeight) {
// Android Chrome address bar has appeared
} else {
// Android Chrome address bar has disappeared
}
} else if(hasOrientationChanged) {
// Orientation change
}
viewportHeight = newViewportHeight;
viewportWidth = newViewportWidth;
isPortrait = viewportHeight > viewportWidth;
}
});
Had the same issue today, turns out there is no easy way to figure out the height of the url bar directly. As far as I know, none of the directly accessible variables in javascript can tell you how much the size of "100vh" really is.
On mobile browsers, 100vh may or may not include the height of the url bar, which leaves us in a tricky situation, if we want to size a div to the exact height of the visible content area of the browser during load.
I figured out a workaround though that worked pretty neat for me, here's what I did:
add a dummy property on your html root element with a size of 100vh. In my case, i used the "perspective" attribute, which worked for me
then you can get the address bar size with the following code:
var addressBarSize = parseFloat(getComputedStyle(document.documentElement).perspective) - document.documentElement.clientHeight
I had a container with dynamic content that had to always have at least viewport's full height (and be scrollable if the content doesnt fit on the screen).
So if you need a fixed height, just replace "min-height" with "height" in my solution.
That's how I dealt with it.
// calculate min-height on init
$(".content-container").css("min-height", `${window.innerHeight}px`);
// recalculate the min-height everytime the bar appears or disappears
$(window).resize(() => {
$(".content-container").css("min-height", `${window.innerHeight}px`);
});
It works for android's address bar and also safari's bars (in safari mobile there can be top and the bottom bar aswell).
Then to make the transition smooth, you can apply a css rule:
.content-container{
transition: min-height 500ms ease;
}

How to Make This Jquery Script Work In Specific Width

I'm beginner to Jquery.
I have a simple piece of code that changes the height of an element to half of the window height.
$(function () {
'use strict';
$('.moubdi3in').height($(window).height());
});
I want to make this script work only when window size is more than 769px. In lesser heights, I want to give the element full window height.
How can I do this?
Thanks
You can use a trinary operator or if to decide what will be the elements height according to the current window height:
$(function () {
'use strict';
var windowHeight = $(window).height();
$('.moubdi3in').height(windowHeight > 769 ? windowHeight / 2 : windowHeight);
});
I want to make this script work only when window size is more than
769px
if($(window).height() <= 769) return; // reject function if less|equal 769px
I want to give the element full window height.
$('.moubdi3in').css('height', $(window).height()); // set windows height to height property of .moubdi3in element

Element dimensions are updating in the DOM but the changes aren't displaying onresize

I'm trying to resize a svg element to fit as large as possible in the browser while maintaining a 100x50 scale. When I inspect the changes made to the DOM, everything checks out fine, but the updated dimensions don't seem to render. How do I fix this problem?
http://jsfiddle.net/Wexcode/SE6d3/show/
var svg = document.getElementById("svg");
resize.call(svg);
window.onresize = function() {
resize.call(svg);
}
function resize() {
this.setAttribute("width", scale(100));
this.setAttribute("height", scale(50));
function scale(value) {
return Math.min(window.innerWidth / 100, window.innerHeight / 50) * value;
}
}
Edit: sq2's answer, which changes the code from
this.setAttribute("width", scale(100));
this.setAttribute("height", scale(50));
to
this.style.width = scale(100);
this.style.height = scale(50);
provides a fix, but is still broken in Firefox.
UPDATE:
Also this http://jsfiddle.net/SE6d3/70/ is working everywhere and resize is working in Chrome and Firefox with proportions 100 to 50
Edit: Rather than setting the width/height attributes, set the width/height CSS style.
You have no problems at attr/style level: try this http://jsfiddle.net/SE6d3/27/
All working normal if firefox and chrome.
I think your problem on level of getting width/height from window.
Try this methods:
getClientHeight = function(){
return document.compatMode=='CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight;
};
getClientWidth = function(){
return document.compatMode=='CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth
};
Not sure why that is intermittently working, very strange and curious to see if there is a better answer.
But... replacing:
this.setAttribute("width", scale(100));
this.setAttribute("height", scale(50));
with:
this.style.width = scale(100);
this.style.height = scale(50);
renders it correctly on screen in Chrome, however I am doubtful that setting style of SVGs is the correct approach.

Setting the minimum size of a JavaScript popup window

Is there any way to set the minimum size of a popup window through JavaScript?
My problem is that when someone makes it as small as he can the content just looks stupid.
When creating pop-ups, you can only set width and height. But since the pop-up was created, it means you can change the height and width of the window when the pop-up loads.
Simply place an onload event inside your pop-up window:
window.onload = function() {
if (document.body.scrollHeight) {
var winWidth = document.body.scrollWidth;
var winHeight = document.body.scrollHeight;
} else if (document.documentElement.scrollHeight) {
var winHeight = document.documentElement.scrollHeight;
var winWidth = document.documentElement.scrollWidth;
} else {
var winHeight = document.documentElement.offsetHeight;
var winWidth = document.documentElement.offsetWidth;
}
window.resizeTo(winWidth, winHeight);
}
edit: Tested in IE7,8, Chrome, Safari 4, Firefox 3. Working, but you might need to take into account the size of menu+address bars and such, as the window size will be the outer size, and this function will find the size of the content. So to be safe you should probably add a couple of pixels, and also turn off scrollbars in the popup to make sure they won't take up any space.
I do not believe that you can set a minimum using the Javascript new window. I know you can set the size and disable the scroll bars and prevent resizing, but that would answer the minimum, but also impose a maximum as well, which you may not be wanting.
Most browsers have a minimum width and height.
Internet Explorer 7
minimum width > 250px
minimum height > 150px
When using windows.open, you can specify the height and width of the window like this:
window.open ("http://www.stackoverflow.com",
"mywindow","menubar=1,resizable=1,width=350,height=250");
It is not the minimum size though, as the window will not be bigger when there is more room. You would have to check screen space yourself for that.
http://www.htmlgoodies.com/beyond/javascript/article.php/3471221
As seen in the link, you can set the minimum size. If you want to scale it so it gets bigger you must to that from within the popupwindow.

Categories