This is a followup question to this quetsion: Get the device width in javascript.
What I'm trying to do, is get the equivalent css of #media (max-width: 600px) in JavaScript.
The accepted answer says to do the following:
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
Is that still correct? Will it work for all devices?
If it's correct, what's the point of checking (window.innerWidth > 0)?
I want to know if it still works. If you look at the last comment on the answer (with 6 upvotes) it says:
How does this have so many upvotes? var width = (window.innerWidth >
0) ? window.innerWidth : screen.width; returns 667 on iphone 6 AND 6
Plus. This solution does not work correctly.
You should be able to do something like this:
if (matchMedia) {
var mq = window.matchMedia("(max-width: 600px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
function WidthChange(mq) {
if (mq.matches) {
//Window width is less than or equal to 600px
} else {
//Window width is greater than 600px
}
}
From your question it seems you are asking for the following (It is a trivial answer but I assume this is what you are asking):
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
is equivalent to:
var width;
if (window.innerWidth > 0)
{
width = window.innerWidth;
}
else
{
width = screen.width;
}
or:
var width = screen.width;
if (window.innerWidth > 0)
{
width = window.innerWidth;
}
they all do the same thing...
from your comment below you may want the following jsFiddle:
(which shows "window.innerWidth" is what you want (size of containing element) - but some browsers don't support it - so "screen.width" becomes the fallback which may not be correct as it is the width of the whole window and not just the containing element)
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
$('#divOutput').html('The width is:' + width + 'px <br>' +
'window.innerWidth = ' + window.innerWidth + 'px & <br>' +
'screen.width = ' + screen.width + 'px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOutput"></div>
if that doesn't help maybe look at:
window.innerWidth can't work on IE7. How to fix via JS and jQuery?
Related
I am trying to set a responsive point in my mobile Webview and did this:
var w = window.innerWidth-40;
var h = window.innerHeight-100;
This works great so far. But the values -40 and -100 are not in the viewport scaling height and width.
When I do this:
var w = window.innerWidth-40vw;
var h = window.innerHeight-100vh;
as it should be to stay responsive and relative to the viewport - the JS does not work anymore.
I think vh and vw works only in CSS ?
How can I achieve this in JS ?
Pleas no JQuery solutions - only JS!
Thanks
Based on this site you can use the following util functions to calculate your desired values as a function of a percent of screen width or height:
function vh(percent) {
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
return (percent * h) / 100;
}
function vw(percent) {
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
return (percent * w) / 100;
}
function vmin(percent) {
return Math.min(vh(percent), vw(percent));
}
function vmax(percent) {
return Math.max(vh(percent), vw(percent));
}
console.info(vh(20), Math.max(document.documentElement.clientHeight, window.innerHeight || 0));
console.info(vw(30), Math.max(document.documentElement.clientWidth, window.innerWidth || 0));
console.info(vmin(20));
console.info(vmax(20));
I used this incredible question in my code!
Try this:
function getViewport() {
var viewPortWidth;
var viewPortHeight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewPortWidth = window.innerWidth,
viewPortHeight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0) {
viewPortWidth = document.documentElement.clientWidth,
viewPortHeight = document.documentElement.clientHeight
}
// older versions of IE
else {
viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
}
return [viewPortWidth, viewPortHeight];
}
Reference: http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
Problem is that JS does not have 40vh, calculate how much pixels is 40vh first to use it. It will throw error when doing 1000 - 40vh
40vh means 40 % of viewport height. So window.innerHeight * 0.4 == 40vh
Also there is no such thing as wh, only vh (% of viewport height)
The simplest way to do this, if you can fully edit the page, is to make a css class that has -40vw and -100vh like so:
CSS:
.class{
width: -40vw;
height: -100vh;
}
JS:
element.classList.add("class");
Note: "classList" is not supported in Internet Explorer 9. If you want it to work in all browsers, use this for JS instead:
function myFunction() {
var element, name, arr;
element = document.getElementById("myDIV");
name = "mystyle";
arr = element.className.split(" ");
if (arr.indexOf(name) == -1) {
element.className += " " + name;
}
}
you just need to surround it in quotes I think.
var w = window.innerWidth = "40vw"
var w = window.innerWidth = "40vw"
this is my solve with you can use CSS;
// calc dynamic customer device height/width
let vh = window.innerHeight * 0.01,
vw = window.innerWidth * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
document.documentElement.style.setProperty('--vw', `${vw}px`);
How to use in CSS ?
If you will use 100vh or 100vw with this method, you should set 100vh/100vw for uncompatible browser.
Examples;
.wrapper{
height: 100vh; /* Fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
}
.slide-container{
height: calc(var(--vh, 1vh) * 100 - var(--menuHeight) - var(--footerHeight));
}
.little-image{
width: calc(var(--vw, 1vw) * 5);
margin-bottom: calc(var(--vh, 1vh) * 1);
}
/* and more.. */
This isn't a universal solution, but it's a much simpler implementation if you're working with a page that is always 100% displayed within the viewport (ie, if the body doesn't have to be scrolled and always matches the window width and height).
let vh = document.body.getBoundingClientRect().height;
This sets the vh variable to the pixel value of the document body with just one line of code.
Useful for game dev and other scenarios where you have the body affixed to the viewport.
get vmin in px
function vmin(){
return window.innerHeight < window.innerWidth ? window.innerHeight: window.innerWidth;
}
How can i detect if some element is visible? For better understading look at the image below.
I want to fire event when the image is half-visible. It would be great if it would work for all browsers and devices (tablets and smartphones).
Jquery.fracs plugin seems to do exactly what you need.
function callback(fracs: Fractions, previousFracs: Fractions) {
if(fracs > 0.5)
doSomething();
};
var fracs = $("img").fracs(callback);
Your Window is between
$(document).scrollTop()
and
$(document).scrollTop() + $(window).height()
If the
$(element).offset().top
falls between those, it should be visible.
EDIT: I am assuming your element (whose visibility is to be determined) is absolutely positioned. If not, it would be a bit more complicated.
EDIT2: This is only to determine visibility in case of vertical offset. For the horizontal version, replace "scrollTop" with "scrollLeft", "height" with "width" and "top" with "left".
There's a neat plugin, jQuery fracs written specifically for this purpose.
You want to check whether the item is viewable from the bottom of the screen or the top. so the logic would be this:
on window scroll event
if item.y is less than scroll.y, calculate amount off screen
if item.y + item.height is greater than scroll.y + scroll.height, calculate amount off screen
deduct both values off the item.height to find the total off screen
create a percentage of this
So in javascript this would work something like this:
var el = document.getElementById('item1'),
rect = el.getBoundingClientRect(),
item = {
el: el,
x: rect.left,
y: rect.top,
w: el.offsetWidth,
h: el.offsetHeight
};
window.addEventListener('scroll', function (e) {
var deduct = 0,
percentage = 0,
x = window.pageXOffset,
y = window.pageYOffset,
w = window.innerWidth,
h = window.innerHeight;
if (item.y < y) {
deduct += (y - item.y);
}
if ((item.y + item.h) > (y + h)) {
deduct += (item.y + item.h) - (y + h);
}
if (deduct > item.h) {
deduct = item.h;
}
percentage = Math.round(((item.h - deduct) / item.h) * 100);
});
I've excluded the support for older browsers, but if you need it it would be:
x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft,
y = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop,
w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var $w = $(window), wh = $w.height(),
top = $w.scrollTop(), bottom = top + wh,
$img = $("#image"),
imgCenter = $img.offset().top + $img.height()/2;
if (imgCenter >= top && imgCenter < bottom) {
// the image is half-visible
}
im trying to get some images to resize automatically when a window resizes.
I have this working with the code below, however I would like to have a little more control over the image such as being able to set a min-height, any ideas??
also maybe wrap the images in a div so there is a little more control? Im not to good with js so any help or explanations would help
$(function() {
var $img = $(".l");
var ratio;
var offsetX = $img.offset().left;
var offsetY = $img.offset().top;
$(window).load(function () {
ratio = $img.width() / $img.height();
$(this).resize();
});
$(window).resize(function () {
var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
var availWidth = viewportWidth - offsetX - 70;
var availHeight = viewportHeight - offsetY - 70;
if (availWidth / availHeight > ratio) {
$img.height(availHeight);
$img.width(availHeight * ratio);
}
else {
$img.width(availWidth);
$img.height(availWidth / ratio);
}
});
});
Just use CSS:
img { width: 100%; }
You can then apply height or min-height as you need.
To see it working, resize the window of this fiddle:
Example fiddle
I have this jQuery code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$( document ).ready( function() {
var $body = $('body'); //Cache this for performance
var setBodyScale = function() {
var scaleFactor = 0.35,
scaleSource = $body.width(),
maxScale = 600,
minScale = 30;
var fontSize = scaleSource * scaleFactor; //Multiply the width of the body by the scaling factor:
if (fontSize > maxScale) fontSize = maxScale;
if (fontSize < minScale) fontSize = minScale; //Enforce the minimum and maximums
$('body').css('font-size', fontSize + '%');
}
$(window).resize(function(){
setBodyScale();
});
//Fire it when the page first loads:
setBodyScale();
});
</script>
But I want to activate this jQuery code only if #media only screen and (min-width : 1025px) and (max-width : 2048px) not after that and not before that.
before 1024px and after 2048px the script should not do anything.
I don't think it is possible to get the #media configuration from javascript.
What you can is obtain the document's width and check its value:
var docWidth = $(document).width();
if (docWidth > 1024 && docWidth < 2048) {
// execute your function
}
I don't know if it required, but if the user resize the window, you might also need to bind to the resize event:
$(window).resize(function(event) {
//execute your function
});
d.
Use the jquery resize event :
$(window).resize(function() {
// Check here the width
width = $(document).width();
if (width > 1024 && width < 2048) {
// do your code
}
});
I think you can do what you want with this
In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.
I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.
My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me?
Edit:
The DIV houses a control that does it's own overflow handling (implements its own scroll bar).
Try this simple, specific function:
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
It does not depend on the current distance from the top of the body being specified (in case your 300px changes).
EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course.
What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:
div {
position: absolute;
top: 300px;
bottom: 0px;
left: 30px;
right: 30px;
}
This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom. Add an overflow:auto; to handle cases where the content is larger than the div.
Edit: #Whoever marked this down, an explanation would be nice... Is something wrong with the answer?
document.getElementById('myDiv').style.height = 500;
This is the very basic JS code required to adjust the height of your object dynamically. I just did this very thing where I had some auto height property, but when I add some content via XMLHttpRequest I needed to resize my parent div and this offsetheight property did the trick in IE6/7 and FF3
If I understand what you're asking, this should do the trick:
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use
// window.innerWidth and window.innerHeight
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("yourDiv").height = windowHeight - 300 + "px";
With minor corrections:
function rearrange()
{
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("foobar").style.height = (windowHeight - document.getElementById("foobar").offsetTop - 6)+ "px";
}
Simplest I could come up...
function resizeResizeableHeight() {
$('.resizableHeight').each( function() {
$(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )
});
}
Now all you have to do is add the resizableHeight class to everything you want to autosize (to it's parent).
inspired by #jason-bunting, same thing for either height or width:
function resizeElementDimension(element, doHeight) {
dim = (doHeight ? 'Height' : 'Width')
ref = (doHeight ? 'Top' : 'Left')
var x = 0;
var body = window.document.body;
if(window['inner' + dim])
x = window['inner' + dim]
else if (body.parentElement['client' + dim])
x = body.parentElement['client' + dim]
else if (body && body['client' + dim])
x = body['client' + dim]
element.style[dim.toLowerCase()] = ((x - element['offset' + ref]) + "px");
}