Add CSS based on window height - javascript

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 */
}

Related

Looking for a better JavaScript/CSS switch

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.

Guidelines for resizing and adjusting for mobile devices using javascript

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

CSS media screen width vs jQuery(window).width()

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/

CSS and jQuery have different widths

I'm, setting up the mobile side of a website at the moment, and I need custom CSS and Javascript for mobile, so in the CSS I have rules using #media screen and (max-width: 500px) { and in Javascript I was going to use if ($(window).width() < 500.
However, if I resize my browser to the exact pixel the mobile CSS starts being used and I console.log($(window).width()); I get 485.
Is this normal behaviour or am I doing something wrong?
Update:
Using this, the values seem to be in sync, only tested in firefox though at the moment.
var scrollBarWidth = false;
function mobileRules() {
if (!scrollBarWidth) {
var widthWithScrollBars = $(window).width();
$('body').css('overflow', 'hidden');
var widthNoScrollBars = $(window).width();
$('body').css('overflow', 'scroll');
scrollBarWidth = widthNoScrollBars - widthWithScrollBars;
console.log('Width: '+widthWithScrollBars+'. Without: '+widthNoScrollBars+'. Scroll: '+scrollBarWidth);
}
console.log($(window).width()+scrollBarWidth+' vs '+globals.mobile_width);
if ($(window).width()+scrollBarWidth < globals.mobile_width) {
console.log('Running mobile rules in jQuery');
}
}
In firefox, media queries consider the width of the scrollbar to be inside the screen width.
This is what gives you the 15px wider screen width.
In webkit based browsers they don't.
If you're interested in why this thing happens, I'll quote this comment of this article :
A problem with Webkit browsers (that aren't following spec) is that the browser can encounter an infinite loop condition caused by media queries, which leads to a browser crash.
For example: >500px overflow-y: scroll, <500px overflow-y: hidden. Size your browser to 505px window width. Since the scroll bar subtracts 15 or so pixels from the width used by the media query, the media query flips you to < 500, but as soon as you hit <500 the scrollbar goes away, and the media query flips you to >500, and then the fun starts because now you have a scroll bar again and you're <500px and you get that style with no scroll bar... Rinse and repeat until the browser finally dies.
Now, write some javascript to calculate the media query max widths, and you have a page that will crash Chrome/Safari as soon as you load it.
My guess is that the spec was written the way it was to prevent this condition. Firefox & Opera are following spec, it's not really their fault you don't agree with spec.

Bootstrap: Responsitive design - execute JS when window is resized from 980px to 979px

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

Categories