I have a bit of JavaScript/JQuery code that I have been tweaking in order to have a webpage switch CSS scripts if the page is resized too small, or if it starts up too small.
The resize seems to work great, but I think i may be cheating on the window.onload statement to make the resize check happen. I can see it when I start to load the page and see it have to "think" before switching to the narrow.css.
I am looking for suggestions on how to make this bit of code preform better, or be less taxing on a mobile connection.
"use strict";
var windowsize = $(window).width();
$(window).resize(function() {
windowsize = $(window).width();
if (windowsize < 600) {
document.getElementById("myCSS").setAttribute("href", "css/narrow.css");
} else {
document.getElementById("myCSS").setAttribute("href", "css/mystyles.css");
}
});
//force window size check at load to kick in if statement
window.onload = $(window).resize();
css media queries are designed for this purpose: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries
To apply this approach with the details in your example you might do something like this:
#media (max-width: 600px) {
/*CSS from css/narrow.css*/
}
#media (min-width: 601px) {
/*CSS from css/mystyles.css*/
}
It is probably best to have #myCSS set originally to the mobile stylesheet, and if the screen is too big, switch to the desktop stylesheet.
No need to wait for the load event to execute; if the JS snippet is after #myCSS, then #myCSS is already in the DOM, and one can just write $(window).resize(); without window.onload =. This should prevent the browser from waiting till everything else is loaded before loading the stylesheet.
Related
I have been having an issue with resizing web pages to fit on mobile devices using JavaScript. Is there a certain width that most programmers use to start changing the resize for mobile devices? Can anyone recommend any guidelines that I should or need to follow when working with mobile devices? I am now being instructed to make sure all web pages are "mobile friendly".
function adjustStyle() {
var width = 0;
// get the width.. more cross-browser issues
if (window.innerHeight) {
width = window.innerWidth;
} else if (document.documentElement && document.documentElement.clientHeight) {
width = document.documentElement.clientWidth;
} else if (document.body) {
width = document.body.clientWidth;
}
// now we should have it
if (width < 650) {
document.getElementById("myCSS").setAttribute("href", "css/narrow.css");
} else {
document.getElementById("myCSS").setAttribute("href", "css/main.css");
}
}
// now call it when the window is resized.
window.onresize = function () {
adjustStyle();
};
For starters, you shouldn't rely on Javascript to make your pages responsive to different resolutions or screens sizes, CSS can handle that for you using media-queries.
Javascript should be used in responsive design only under these circumstances:
You have an extreme design feature that is impossible to pull off correctly in CSS
You want to enhance your web page by adding in some interactions, animations or custom behaviors.
You have an experimental website where users are expecting something out of the ordinary
You are willing to warn your users if javascript is required to display/run your page properly.
It is best practice to only use javascript to enhance your page after you have written your responsive layouts in CSS, that way, your site is still functional if javascript is turned off in the browser.
"Progressive enhancement" is a popular technique for web developers who want to get the page looking nicely while assuming Javascript is turned off, so that users without javascript will still get a nice experience, then, progressive-enhancement in javascript means that the user can be ensured an even better experience if they have javascript turned on, because they might see some nice animations, and cool parallax scrolling, etc.
With that said, your question was directly asking about using javascript for responsive design, so from there, the advice is simple:
Use jQuery's bind() or resize()functions to listen for browser resize events:
$(window).resize(function() {
// handle layout here
// change widths, heights, positions, etc
});
$(window).bind("resize", function(){
// handle layout here
// change widths, heights, positions, etc
});
And from there, you can effect the width's height's and positions of your elements, or assign CSS properties to them, depending on your design.
As for good "breakpoints" (screen sizes to watch for in your responsive layouts), you can refer to this guide: Media Queries for Common Device Breakpoints.
I tend to start somewhere around here, and then tweak as I go:
Mobile: width: 320px - 750px
Tablets: width: > 750px - 1024px
Laptops/Desktops: width: > 1024px
And then I test on multiple devices, and make changes accordingly, your final design will dictate the final numbers you choose as your breakpoints.
Hope this helps.
I typically use a width of 600 to adjust for mobile devices.
Make sure to add this meta tag inside the <head> tag:
<meta name="viewport" content="width=device-width">
This should make the page render at a reasonable size.
Add this <style> tag inside the <head> tag:
<style>
img {
max-width: 100%;
}
</style>
I think this will make sure all images don't render any wider than the app's webview's viewport.
(If that doesn't work, try width: 100%; instead. That'll definitely make all images be as wide as the viewport, and therefore no wider.)
You can also try the #media tags in your css, they allow you to completely reprogram it depending on the resolution:
#media screen and (max-width: 600px) {
.button {
width:300px;
}
}
then for different resolutions above mobile
#media screen (min-width: 600px) and (max-width: 1200px) {
.button {
width:500px;
}
}
But you can always use jquery's
$(window).resize(...) which binds a callback for the resize event or triggers this event.
Bind a callback function, if the users resizes the browser window:
$(window).resize(function() {
alert('resize handler called');
});
If you want to call all listeners manually (without any parameters):
$(window).resize();
I am making some nifty CSS3 animations assisted by some jquery and in the process of making those animated functions responsive, I stumbled upon a strange thing, very strange indeed.
The media query I am calling states
#media screen and (max-width: 1024px)
But when I call the window width using JavaScript it reveals that it actually triggers at window width 1009px
console.log('window.size: '+$(document).width());
I must admit that I am completely confused by this one, anyone have any bright idea? :)
I have had the same issue, I believe this is something to do with jQuery, the solution I have found that may be a little more light weight that a whole function, is to use
window.innerWidth
instead of using jQuery to select the body/window width.
Here is a fiddle of it working without the jQuery selector
http://jsfiddle.net/wf40d79x/
using
$(window).resize(function() {
console.log(window.innerWidth);
});
and here is it breaking, WITH the jQuery selector
http://jsfiddle.net/4bgzf1Lp/2/
using
$(window).resize(function() {
console.log($(window).width());
});
You'll see in the console as you bring the screen down to 600px the as the media query pops, using javascript only the console will agree with the width, whereas with jQuery it will be about 17px smaller.
Hope this helps.
After #Pete pointed me in the right direction and ispired by a small pice of code I found somewhere, I came up with this:
(I would give credits to the person who came up with the below if I could remember where I found it, but posting it here in case someone else needs a similar solution)
function scrollBarWidth() {
jQuery("html").css("overflow", 'hidden');
var width = jQuery("html").width();
jQuery("html").css("overflow", 'scroll');
width -= jQuery("html").width();
if(!width){
width = document.body.offsetWidth - document.body.clientWidth;
jQuery("body").css("overflow", '');
}
return width;
}
I came across a solution which is brilliant to verify which media file is active. Add a selector which changes state or font in css media file and check in js to check if state has changed.
.width-verify{
display: none;
}
#media only screen and (min-width: 768px) {
.width-verify {
display: block;
}
}
JS:
if ($('.width-verify').css('display') === 'block') {
//...
}
Thanks to http://www.acoupleofnerds.com.au/2014/09/3-ways-fix-jquerys-window-width-method-matching-media-queries/
I was trying something with JavaScript and media queries. I want to change some elements with JavaScript, like switching elements etc.
When the browser/device width is 320px I want to do something.
I came up with the following, but this doesn't work:
if (screen.width < 320){
$('input[type="text"]').insertAfter('label');
$('input[type="text"]').eq(1).remove();
$('input[type="text"]').eq(2).remove();
}
What am I doing wrong?
When I would like to do this for some changes of my CSS it looks like this:
#media only screen and (max-width : 400px) { }
And the example above I want to convert to JavaScript.
You can call media queries inside JavaScript:
function resize() {
if (window.matchMedia('only screen and (max-width: 400px)').matches) {
document.body.style.background = 'red';
} else if (window.matchMedia('only screen and (min-width: 401px) and ' +
'(max-width: 600px)').matches) {
document.body.style.background = 'blue';
} else {
document.body.style.background = 'yellow';
}
}
window.addEventListener('resize', resize, false);
resize();
Yes. You can do so by using $(window).width().
if ($(window).width() < 320) {
$('input[type="text"]').insertAfter('label');
$('input[type="text"]').eq(1).remove();
$('input[type="text"]').eq(2).remove();
}
Also, if you want to check if a resize has happened without refreshing, use $(window).resize().
Here's an example jsFiddle of resize in use.
Please refer below URL:
Phonegap - reliable page width detection?
You can use Navigator object to detect the devices in jquery.
Yes you can. Whilst media queries are great for css sometimes we need to load js based on the device size.
Media Match written by Paul Irish is a great tool to do this. It is used in Modernizr a feature detection library.
I have a pop up window that looks great as long as the viewer is using a large screen (over 750px high). I'd like to add a CSS selector to push up the important content (and obscure the title and intro info which is expendable) for people viewing on laptops. I thought the easiest way would be to raise the body tag up -180 px.
I thought it would be a good job for my first shot at jQuery but I can't seem to get it to work. I've tried:
if($(window).height() <= 650)
$(body).css("margin-top","-180px");
and also
$(document).ready(function() {
if ($(window).height() < 670) {
$("body").css('margin-top', '-180px');
}
else {
$("body").css('margin-top', '0px');
}
});
but neither seems to work. How can I change the body styling based on the current window height?
Just use media queries to serve up differing versions or styles:
#media only screen
and (max-height: 650px) {
/* Styles */
}
I'm using last Twitter's Bootstrap. I would like to execute a certain JS function (showing tooltip once) when my window's width is lower than 980px (as you know, on this size Bootstrap modifies Navbar and hides standard menu items) – window is from 768 to 979, to be short. I know that
#media (min-width: 768px) and (max-width: 979px) {...}
this option may be used to catch the event. However, it may be used only for changing exiting styles like
body {background-color:#ccc;}
And I need to launch JS-function, or add or remove a specific style for element. I've tried:
<script>
window.onresize = function () {
if (window.outerWidth == 980) {alert('');}
};
</script>
but this solution is so slow, and even hangs a browser window. So, is there any solution to catch this event, when window is resized to 979px from GREATER side and execute a JS-function?
Thanks to all!
outerWidth is a method so you're missing ():
if (window.outerWidth() == 980)
In any case if you're using jQuery:
$(window).resize(function() {
if ($(this).width() < 981) {
//do something
}
});