I want to provide my visitors the ability to see images in high quality, is there any way I can detect the window size?
Or better yet, the viewport size of the browser with JavaScript? See green area here:
Cross-browser #media (width) and #media (height) valuesÂ
const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
window.innerWidth and window.innerHeight
gets CSS viewport #media (width) and #media (height) which include scrollbars
initial-scale and zoom variations may cause mobile values to wrongly scale down to what PPK calls the visual viewport and be smaller than the #media values
zoom may cause values to be 1px off due to native rounding
undefined in IE8-
document.documentElement.clientWidth and .clientHeight
equals CSS viewport width minus scrollbar width
matches #media (width) and #media (height) when there is no scrollbar
same as jQuery(window).width() which jQuery calls the browser viewport
available cross-browser
inaccurate if doctype is missing
Resources
Live outputs for various dimensions
verge uses cross-browser viewport techniques
actual uses matchMedia to obtain precise dimensions in any unit
jQuery dimension functions
$(window).width() and $(window).height()
You can use the window.innerWidth and window.innerHeight properties.
If you aren't using jQuery, it gets ugly. Here's a snippet that should work on all new browsers. The behavior is different in Quirks mode and standards mode in IE. This takes care of it.
var elem = (document.compatMode === "CSS1Compat") ?
document.documentElement :
document.body;
var height = elem.clientHeight;
var width = elem.clientWidth;
I looked and found a cross browser way:
function myFunction(){
if(window.innerWidth !== undefined && window.innerHeight !== undefined) {
var w = window.innerWidth;
var h = window.innerHeight;
} else {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
}
var txt = "Page size: width=" + w + ", height=" + h;
document.getElementById("demo").innerHTML = txt;
}
<!DOCTYPE html>
<html>
<body onresize="myFunction()" onload="myFunction()">
<p>
Try to resize the page.
</p>
<p id="demo">
</p>
</body>
</html>
I know this has an acceptable answer, but I ran into a situation where clientWidth didn't work, as iPhone (at least mine) returned 980, not 320, so I used window.screen.width. I was working on existing site, being made "responsive" and needed to force larger browsers to use a different meta-viewport.
Hope this helps someone, it may not be perfect, but it works in my testing on iOs and Android.
//sweet hack to set meta viewport for desktop sites squeezing down to mobile that are big and have a fixed width
//first see if they have window.screen.width avail
(function() {
if (window.screen.width)
{
var setViewport = {
//smaller devices
phone: 'width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no',
//bigger ones, be sure to set width to the needed and likely hardcoded width of your site at large breakpoints
other: 'width=1045,user-scalable=yes',
//current browser width
widthDevice: window.screen.width,
//your css breakpoint for mobile, etc. non-mobile first
widthMin: 560,
//add the tag based on above vars and environment
setMeta: function () {
var params = (this.widthDevice <= this.widthMin) ? this.phone : this.other;
var head = document.getElementsByTagName("head")[0];
var viewport = document.createElement('meta');
viewport.setAttribute('name','viewport');
viewport.setAttribute('content',params);
head.appendChild(viewport);
}
}
//call it
setViewport.setMeta();
}
}).call(this);
I was able to find a definitive answer in JavaScript: The Definitive Guide, 6th Edition by O'Reilly, p. 391:
This solution works even in Quirks mode, while ryanve and ScottEvernden's current solution do not.
function getViewportSize(w) {
// Use the specified window or the current window if no argument
w = w || window;
// This works for all browsers except IE8 and before
if (w.innerWidth != null) return { w: w.innerWidth, h: w.innerHeight };
// For IE (or any browser) in Standards mode
var d = w.document;
if (document.compatMode == "CSS1Compat")
return { w: d.documentElement.clientWidth,
h: d.documentElement.clientHeight };
// For browsers in Quirks mode
return { w: d.body.clientWidth, h: d.body.clientHeight };
}
except for the fact that I wonder why the line if (document.compatMode == "CSS1Compat") is not if (d.compatMode == "CSS1Compat"), everything looks good.
If you are looking for non-jQuery solution that gives correct values in virtual pixels on mobile, and you think that plain window.innerHeight or document.documentElement.clientHeight can solve your problem, please study this link first: https://tripleodeon.com/assets/2011/12/table.html
The developer has done good testing that reveals the problem: you can get unexpected values for Android/iOS, landscape/portrait, normal/high density displays.
My current answer is not silver bullet yet (//todo), but rather a warning to those who are going to quickly copy-paste any given solution from this thread into production code.
I was looking for page width in virtual pixels on mobile, and I've found the only working code is (unexpectedly!) window.outerWidth. I will later examine this table for correct solution giving height excluding navigation bar, when I have time.
This code is from http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
NB : to read the width, use console.log('viewport width'+viewport().width);
There is a difference between window.innerHeight and document.documentElement.clientHeight. The first includes the height of the horizontal scrollbar.
A solution that would conform to W3C standards would be to create a transparent div (for example dynamically with JavaScript), set its width and height to 100vw/100vh (Viewport units) and then get its offsetWidth and offsetHeight. After that, the element can be removed again. This will not work in older browsers because the viewport units are relatively new, but if you don't care about them but about (soon-to-be) standards instead, you could definitely go this way:
var objNode = document.createElement("div");
objNode.style.width = "100vw";
objNode.style.height = "100vh";
document.body.appendChild(objNode);
var intViewportWidth = objNode.offsetWidth;
var intViewportHeight = objNode.offsetHeight;
document.body.removeChild(objNode);
Of course, you could also set objNode.style.position = "fixed" and then use 100% as width/height - this should have the same effect and improve compatibility to some extent. Also, setting position to fixed might be a good idea in general, because otherwise the div will be invisible but consume some space, which will lead to scrollbars appearing etc.
For detect the Size dynamically
You can do it In Native away, without Jquery or extras
console.log('height default :'+window.visualViewport.height)
console.log('width default :'+window.visualViewport.width)
window.addEventListener('resize',(e)=>{
console.log( `width: ${e.target.visualViewport.width}px`);
console.log( `height: ${e.target.visualViewport.height}px`);
});
This is the way I do it, I tried it in IE 8 -> 10, FF 35, Chrome 40, it will work very smooth in all modern browsers (as window.innerWidth is defined) and in IE 8 (with no window.innerWidth) it works smooth as well, any issue (like flashing because of overflow: "hidden"), please report it. I'm not really interested on the viewport height as I made this function just to workaround some responsive tools, but it might be implemented. Hope it helps, I appreciate comments and suggestions.
function viewportWidth () {
if (window.innerWidth) return window.innerWidth;
var
doc = document,
html = doc && doc.documentElement,
body = doc && (doc.body || doc.getElementsByTagName("body")[0]),
getWidth = function (elm) {
if (!elm) return 0;
var setOverflow = function (style, value) {
var oldValue = style.overflow;
style.overflow = value;
return oldValue || "";
}, style = elm.style, oldValue = setOverflow(style, "hidden"), width = elm.clientWidth || 0;
setOverflow(style, oldValue);
return width;
};
return Math.max(
getWidth(html),
getWidth(body)
);
}
If you are using React, then with latest version of react hooks, you could use this.
// Usage
function App() {
const size = useWindowSize();
return (
<div>
{size.width}px / {size.height}px
</div>
);
}
https://usehooks.com/useWindowSize/
It should be
let vw = document.documentElement.clientWidth;
let vh = document.documentElement.clientHeight;
understand viewport: https://developer.mozilla.org/en-US/docs/Web/CSS/Viewport_concepts
shorthand for link above: viewport.moz.one
I've built a site for testing on devices: https://vp.moz.one
you can use
window.addEventListener('resize' , yourfunction);
it will runs yourfunction when the window resizes.
when you use window.innerWidth or document.documentElement.clientWidth it is read only.
you can use if statement in yourfunction and make it better.
You can simply use the JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query. This is the best and most reliable way to detect mobile devices.
The following example will show you how this method actually works:
<script>
$(document).ready(function(){
if(window.matchMedia("(max-width: 767px)").matches){
// The viewport is less than 768 pixels wide
alert("This is a mobile device.");
} else{
// The viewport is at least 768 pixels wide
alert("This is a tablet or desktop.");
}
});
</script>
The problem
I'm using javascript to calculate widths of elements to achieve the layout I'm after. The problem is, I don't want to load the code on smaller screen sizes (when the screen width is less than 480px for example). I'd like this to work on load and on browser/viewport resize.
I'd consider small screen devices 'the default' and working up from there. So, none of the following script is called by default, then if the browser width is greater than 480px (for example), the following script would be called:
The code
$(document).ready(function() {
//Get the figures width
var figure_width = $(".project-index figure").css("width").replace("px", "");
//Get num figures
var num_figures = $(".project-index figure").length;
//Work out how manay figures per row
var num_row_figures = Math.ceil(num_figures / 2);
//Get the total width
var row_width = figure_width * num_row_figures;
//Set container width to half the total
$(".project-index").width(row_width);
x = null;
y = null;
$(".project-index div").mousedown(function(e) {
x = e.clientX;
y = e.clientY;
});
$(".project-index div").mouseup(function(e) {
if (x == e.clientX && y == e.clientY) {
//alert($(this).next().attr("href"));
window.location.assign($(this).next().attr("href"));
}
x = y = null;
});
});
// Drag-on content
jQuery(document).ready(function() {
jQuery('#main').dragOn();
});
The extra bit
The slight difference on larger screens is to do with the browser/viewport height. This is in regards to the line:
var num_row_figures = Math.ceil(num_figures / 2);
You can see once the calculation has a value, it divides it by 2. I only want this to happen when the browser/viewport height is above a certain amount - say 600px.
I'd be happy with this being the 1st state and then the value is divided by 2 if the height is greater than 600px if it's easier.
Can anyone help me/shed some light on how to manage my script this way. I know there's media queries for managing CSS but I can't seem to find any resources for how to manage javascript this way - hope someone can help.
Cheers,
Steve
You can use window.matchMedia, which is the javascript equivalent of media queries. The matchMedia call creates a mediaQueryList object. We can query the mediaQueryList object matches property to get the state, and attach an event handler using mediaQueryList.addListener to track changes.
I've added an example on fiddle of using matchMedia on load and on resize. Change the bottom left pane height and width (using the borders), and see the states of the two queries.
This is the code I've used:
<div>Min width 400: <span id="minWidth400"></span></div>
<div>Min height 600: <span id="minHeight600"></span></div>
var matchMinWidth400 = window.matchMedia("(min-width: 400px)"); // create a MediaQueryList
var matchMinHeight600 = window.matchMedia("(min-height: 600px)"); // create a MediaQueryList
var minWidth400Status = document.getElementById('minWidth400');
var minHeight600Status = document.getElementById('minHeight600');
function updateMinWidth400(state) {
minWidth400Status.innerText = state;
}
function updateMinHeight600(state) {
minHeight600Status.innerText = state;
}
updateMinWidth400(matchMinWidth400.matches); // check match on load
updateMinHeight600(matchMinHeight600.matches); // check match on load
matchMinWidth400.addListener(function(MediaQueryListEvent) { // check match on resize
updateMinWidth400(MediaQueryListEvent.matches);
});
matchMinHeight600.addListener(function(MediaQueryListEvent) { // check match on resize
updateMinHeight600(MediaQueryListEvent.matches);
});
#media screen and (max-width: 300px) {
body {
background-color: lightblue;
}
}
So i searched a bit and came up with this example from w3 schools .http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_media_example1
i think this is something you are trying to achieve.
For pure js , you can get the screen width by screen.width
I want to report the screen size of a mobile device and update on orientation change but am getting all sorts of strange errors e.g. width almost always 980px.
This works fine on desktop when resizing but not mobile (reporting landscape or portrait is fine though)
Tried on ipad, samsung galaxy tab, google nexus phone and iphone 4
Here's what I'm using:
// get dimensions
_getScreenWidth = function() {
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
var el = document.getElementById('dimensions');
_handleOrientation();
el.innerHTML = 'Width: '+screenWidth +' :: Height: '+screenHeight + "<br /><br />" + _doc_element.className;
};
// portait or landscape
_handleOrientation = function() {
if (device.landscape()) {
_removeClass("portrait");
return _addClass("landscape");
} else {
_removeClass("landscape");
return _addClass("portrait");
}
};
// resize event
var resizeTimeout;
window.onresize = function() {
clearTimeout(resizeTimeout);
// handle normal resize
resizeTimeout = setTimeout(function() {
_getScreenWidth();
}, 250); // 250ms delay
}
You will not get width in physical pixels. Instead, you'll receive "CSS pixels". This is why you getting strange errors. For orientation detecting, you can use "CSS pixels", just compare width to height.
I'm not sure what device.landscape() is supposed to be, but the device object doesn't exist, at least not in standard browsers.
all sorts of strange errors
In my case, that was due to undefined _addClass and _removeClass functions, _doc_element object and as mentioned above, device.landscape().
To fix device.landscape(), you can define landscape as a mode where width > height. Then it's just a simple comparison:
isLandscape = function() {
return window.innerWidth > window.innerHeight;
}
Here is example on jsfiddle with all of the errors fixed. Tested on iPhone 6 and it's setting correct classes.
Is there any way to get the browser width and height after a user has resized the window. For example if the window is 1920 by 1080 and the user changes the window to 500 by 500 is there any way to get those two new values in JavaScript or jquery?
Pure Javascript answer:
var onresize = function() {
//your code here
//this is just an example
width = document.body.clientWidth;
height = document.body.clientHeight;
}
window.addEventListener("resize", onresize);
This works fine on chrome. However, it works only on chrome. A slightly more cross-browser example is using the event target properties "outerWidth" and "outerHeight", since in this case the event "target" is the window itself. The code would be like this
var onresize = function(e) {
//note i need to pass the event as an argument to the function
width = e.target.outerWidth;
height = e.target.outerHeight;
}
window.addEventListener("resize", onresize);
This works fine in firefox and chrome
Hope it helps :)
Edit: Tested in ie9 and this worked too :)
If you need to know these values to do layout adjustments, I bet you plan on listening to those values. I recommended using the Window.matchmedia() API for that purpose instead.
It is much more performant and is basically the JS equivalent of CSS media queries.
Very quick example of use:
if (window.matchMedia("(max-width: 500px)").matches) {
/* the viewport is less than or exactly 500 pixels wide */
} else {
/* the viewport is more than 500 pixels wide */
}
You can also setup a listener that'll get called every time the state of the matches property changes.
See MDN for description and example of using a listener.
It's possible by listening to resize event.
$(window).resize(function() {
var width = $(window).width();
var height = $(window).height();
})
You can use the JQuery resize() function. Also make sure you add the same resize logic to reload event. If user reloads in the sized window your logic won't work.
$(window).resize(function() {
$windowWidth = $(window).width();
$windowHeight = $(window).height();
});
$(document).ready(function() {
//same logic that you use in the resize...
});
Practically, I use this and it helps me a lot:
var TO = false;
var resizeEvent = 'onorientationchange' in window ? 'orientationchange' : 'resize';
$(window).bind(resizeEvent, function() {
TO && clearTimeout(TO);
TO = setTimeout(resizeBody, 200);
});
function resizeBody(){
var height = window.innerHeight || $(window).height();
var width = window.innerWidth || $(window).width();
alert(height);
alert(width);
}
You can use the resize event, along with the height() and width() properties
$(window).resize(function(){
var height = $(window).height();
var width = $(window).width();
});
See some more examples here
Use jQuery resize method to listen window size change . inside callback you can get height and width.
$(window).resize(function(){
var width = $(window).width();
var height = $(window).height();
});
Simplest way to get real width and height of an element after window resize as the follow:
<div id="myContainer">
<!--Some Tages ... -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function () {
$(window).resize(function () {
//The below two lines of codes more Important to clear the previous settings to get the current measure of width and height
$('#myContainer').css('height', 'unset');
$('#myContainer').css('width', 'unset');
var element = $('#myContainer');
var height = element.height();
var width = element.width();
//Below two lines will includes padding but not border
var innerHeight = element.innerHeight();
var innerWidth = element.innerWidth();
//Below two lines will includes padding, border but no margin
var outerHeight = element.outerHeight();
var outerWidth = element.outerWidth();
//Below two lines will includes padding, border and margin
var outerHeight = element.outerHeight(true);
var outerWidth = element.outerWidth(true);
});
});
</script>
You can use the event object to get the height and width, I use destructuring assignment and the target points to window:
const handleGetDim = ({ target }) => ({
width: target.innerWidth,
height: target.innerHeight,
});
window.addEventListener('resize', handleGetDim);
I am making a login page in which I use a little javascript and jquery to vertically align the login box.
I also have an event on resize() to put the box in the middle again.
But, with resize(), everytime the user resize the window, the function is fired and this is a kind of ugly :))
So, I would like to know if there is a way to fire the function only on vertical resize.
Thank you
It will fire every time, but you can track the width to check for only vertical resizing:
// track width, set to window width
var width = $(window).width();
// fire on window resize
$(window).resize(function() {
// do nothing if the width is the same
if ($(window).width()==width) return;
// update new width value
width = $(window).width();
// ... your code
});
Instead of comparing heights for each situation where you want to detect vertical resize, you can create reusable events for horizontal and vertical resizing like this:
// Horizontal and vertical window resize events.
(function () {
var win = jQuery(window),
prev_width = win.width(),
prev_height = win.height();
win.on('resize', function () {
var width = win.width(),
height = win.height();
if (width !== prev_width) {
win.trigger('hresize');
}
if (height !== prev_height) {
win.trigger('vresize');
}
prev_width = width;
prev_height = height;
});
})();
That way you can just drop that code in place once, and then use the events like this:
$(window).on('hresize', function () {
// handle horizontal resizing
});
$(window).on('vresize', function () {
// handle vertical resizing
});
Got better solution:
$('#element').resizable({
stop: function( event, ui ) {
$('#element').height(ui.originalSize.height);
}
});
As a complement to Doublesharp's useful answer:
In my case, window.outerWidth worked better, and was stable to vertical resizes.
Indeed, I had some troubles with $(window).width() : it (strangely!) happened to be modified also when I only resized vertically.