how to get width of a mobiles using javascript - javascript

so I try to get the width of the device using jquery I made responsive website with 2 interface for laptop and mobiles but the problem is it doesn't work in mobile even the dimension of the div test was out of size in mobiles please help me the code that I use for redirecting is below with comments
<html>
<head>
<script src="./js/jquery-3.2.1.js"></script>
</head>
<body>
<div id='test' style=" width: 2.54cm; height:2.54cm;"></div>
//this div dimension works on laptop it measure exactly 2.54cm or 1nch
//using ruler but in mobiles it shrink and out of measure
<script>
//as you see I get the width of the div to get the pixel per inch
var sqw=$('#test').width();
var sqh=$('#test').height();
//and I get the total width of the document
var dheight=$(document).height();
var dwidth=$(document).width();
var w=dwidth/sqw;
//and I divide the total width of the document to pixel per inch
//the problem is the mobile show 10.98 inch where the mobile I use is
//miniFlare S5 cherrymobile with width of just 2.5 inches
if(w<=7) {
window.location.replace("./m_index.php");
} else {
window.location.replace("./d_index.php");
}
</script>
</body>
</html>

Your are using jQuery. From the docs .width() they say:
This method is also able to find the width of the window and document.
// Returns width of browser viewport
$( window ).width(); // <- this is the one you are looking for!
// Returns width of HTML document
$( document ).width();

var dwidth = window.innerWidth;
var dheight = window.innerHeight;
would do the job

You can get cross platform using the following script:
const w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
const h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)

please try below code, it may satisfy your requirement
<script>
getScreensize(){
var sqw=$("body,html").width();
if(sqw<768){
//mobile screen logic
}
else{
//desktop screen logic
}
}
$(window).resize(function(){
getScreensize();
})
</script>

Related

How should I write the width of the body of my document as a condition in JavaScript? [duplicate]

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>

jQuery Script creates infinite loop in Firefox (only)

I wrote a jQuery Script which checks the window size and increases the outer wrapper to fit perfectly into the users window.
function reSize($target){
$target.css('width', $(window).width()+'px');
}
$(document).ready(function(){
setTimeout(function() {
$(window).bind('resize', reSize($('#blocker')));
$(window).trigger('resize');
while($(window).height() < $('.newcontainer').height()+30){
$('.newcontainer').css('width', $('.newcontainer').width() - 10 +'px');
}
$('#chatfenster').css('height', $('.newcontainer').height() - 260 +'px');
$('#userlist').css('height', $('.newcontainer').height() - 350 +'px');
}, 100);
});
It works very smooth in Chrome and Safari but in Firefox it's freezing and I don't know why. Sometimes I feel like Firefox is the new IE.
http://design.maxxcoon.com/bestlife/webinar_chat/ (don't open this link in firefox because it crashes the browser)
Can anybody help me please?
Thanks in advance
This part is very unreliable:
while($(window).height() < $('.newcontainer').height()+30){
$('.newcontainer').css('width', $('.newcontainer').width() - 10 +'px');
}
You are checking the height of the window against the height of the first element found with a class of newcontainer. As long as the height of the window is smaller than that height plus 30 pixels, you set the width of all elements with class="newcontainer" to 10 less than the width of the first one of them.
If your condition is for one dimension (height) and the changes you make is to another dimension (width), the loop will run either never, or probably forever, or possibly randomly...
If there is a maximum height or a maximum width for your .newcontainer elements, you should instead calculate the allowed values for height or width and set them once, not in a loop! Something like this, maybe:
var windowHeight = $(window).height();
var maximumContainerHeight = windowHeight - 30;
$('.newcontainer').css('height', maximumContainerHeight + 'px');
However, I do not know if you want to set width or height, so I'm guessing.
If what you are doing is really setting the width of something, hoping that the layout engine will affect the height as a side-effect, you are going at this the very wrong way.
Another, better, solution is to use modern CSS solutions, like flexbox, to let the browser automatically handle all layout issues.
Figured it out without a loop.
May be helpful for others.
<script type="text/javascript">
function reSize($target){
$target.css('width', $(window).width()+'px');
}
$(document).ready(function(){
setTimeout(function() {
$(window).bind('resize', reSize($('#blocker')));
$(window).trigger('resize');
var windowSize = $(window).height();
var containerHeight = $('.newcontainer').height();
var containerWidth = $('.newcontainer').width();
if(containerHeight > windowSize){
var pixelToMuch = containerHeight - windowSize;
var divFactor = pixelToMuch * 1.67;
var newWidth = containerWidth - divFactor;
$('.newcontainer').css('width',newWidth+'px');
}
$('#chatfenster').css('height', $('.newcontainer').height() - 260 +'px');
$('#userlist').css('height', $('.newcontainer').height() - 350 +'px');
}, 100);
});
</script>

adjust responsive size of iframe with jquery

Hello I'm trying to adjust the size of youtube videos in my web. I want them to be responsive that I'm using jquery to do that. I have done it successfully but the thing is I want the height of youtube video to be decreased. Right now, it's too big. When I try to do it, the responsiveness feature is removed. Can you check how I can decrease the size of the video and keep the responsiveness?
<script>
function update_iframe_size(){
var parent_id = $("iframe").parent().attr("id");
if (parent_id == "main_video") {
var parent_class = $("iframe").parent().attr("class");
var parent_width = $("iframe").parent().width();
console.log(parent_class);
var width = $("iframe").css("width"); // $("iframe").width();
var height = $("iframe").css("height");
var ratio = parseInt(height)/parseInt(width);
var new_height = parseInt(parent_width) * ratio
$("iframe").css("width", parent_width);
$("iframe").css("height", new_height);
}
}
update_iframe_size()
$(window).bind("resize", function(){
// alert("reized");
update_iframe_size();
});
</script>
I tried to decrease the height that I did $("iframe").css("height", new_height*0.7);
but then the height is set to the one I want. However responsiveness gets messed up.
Refer following link: iFrame always take height and width 100% depends on parent div/element which is position relative.
http://jsfiddle.net/masau/7wrhm/

hide div elements when size gets too large

I am building a breadcrumb structure and the elements are getting large.
I would like to hide several breadcrumbs when the size of the breadcrumbs is bigger than the available size. Which command can i use to check if the size of a div is greater than the available space. I have tried to capture an overflow event but this did not work. The .width on my div always return the full size of the screen although when i debug in chrome is says a smaller value...
any help is much appreciated.
Thanks
Edit:
function trimBreadcrumbs()
{
var x = document.getElementById("mnav-emtUl");
var width = x.offsetWidth;
alert(width);
}
this return the full width of the screen although in google chrome it says 200px...
<p id="demo">Click the button to display this window's height and width (NOT including toolbars and scrollbars).</p>
<button onclick="myFunction()">Try it</button>
function myFunction()
{
var w = window.innerWidth;
var h = window.innerHeight;
x = document.getElementById("demo");
x.innerHTML="Width: " + w + " Heigth: " + h;
}
if you didn't set width, it is inherited as width=100%. So this is absolutly correct. Set display:inline-block; for you're breadcumb navigation and it will return the real size.

Get browser width and height after user resizes the window

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

Categories