I have a div set to 100% width, and when the page is being looked at 1024 resolution the width should change from 100% to 1000px, I got it working properly with #media queries and works fine on FF, safari chrome. But ie8 and below ignores it, is there any other to try to get the div to change the width from 100% to 1000px at 1024 resolution on IE?
I tried this with jquery but doesn't work.
$(document).ready(function(){
if ($(window).width() < 1024) {
$('#content')css('width','1000px')
} else {
$('#content')css('width','100%')
};
}
media queries are CSS3. Means not supported by IE8 and lower. But take a look here, that brings support for media queries to IE.
$(document).load($(window).bind("resize", changeWidth));
function changeWidth( e ) {
if($(window).width()<1024)
{
$('#content').css('width','1000px');
} else {
$('#content').css('width','100%');
}
}
jsFiddle
Why not just set this in CSS:
width: 100%;
max-width: 1000px;
It's infinitely more efficient than any JS/jQuery solution, I can assure you.
you can use this code :
$(window).resize(function () {
var width = screen.width;
var height = screen.height;
if (width <= 1024) {
//somecode
} else {
//somecode
}
});
however,as Sven Bieder mentioned CSS Media Queries are better than for Responsive Design.
Related
i want to stop a jquery script when window size is smaller than 500px
can you help me.
i have tried to write a var from 0 to 1 when window size is smaller than 500px
and then add this with a if() function. it doesn't work.
the script that i want to stop running:
[jsfiddle][1]
thx for your help!
ehm yeah stackoverflow i want to text here 10000 words to describe my problem - so sorry i can describe
[1]: http://jsfiddle.net/fg5dcuzm/1/
You can use resize() function:
$(window).resize(function() {
var w = $(window).width();
if (w < 500) {
// stop script
}
});
Or you can run your script only if window is bidder that 500px:
$(window).resize(function() {
var w = $(window).width();
if (w > 500) {
yourFunction();
}
});
$(window).resize(function() {
if($('body').width()<500){
alert('dont do it');
}else{
alert('do it');
}
});
Maybe this helps.
Sorry I haven't reviewed your code well to know why Javascript is not working, but I sometimes hack such things with Css.
Using "!important" will make javascript styles not work when the window width is smaller than 500px:
#media (max-width: 500px) {
.two, .one {
left: 0 !important;
}
}
I notticed when resizing the window, that the effects applied from the responsive #media querys and the effects applied from the jQuery are not at the same point of width.
Is is dued to the browser? Is there a solution for that, or a way to calculate the difference between CSS and JS?
My CSS:
#media only screen
and (min-width : 768px)
and (max-width : 1024px) { }
My jQuery:
$(document).ready(function(){
if($(this).width() < 1024 && $(this).width() > 768) {
} else {
}
$(window).on('resize', function(){
if($(this).width() < 1024 && $(this).width() > 768) {
} else {
}
});
});
To avoid this difference at the moment, my solution is something like that: I have a #selector declared with the display:none when it's between 768px and 1024px. Then, in the jQuery code, instead of using the size < 1024 and > 768 I'm using this:
if($("#selector").is(":hidden")) { }
But, is there a better way to combine width from the #media querys and the jQuery without differences? Thanks.
UPDATE: I already found a solution explained here: https://stackoverflow.com/a/11310353/3018860. That occurs because «the CSS is using the device width, but the JS is using the document width».
I'm trying to write a script to change the width of the page, considering user's client width.
It's something like this:
function adjustWidth() {
width = 0;
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;
}
if (width < 1152) {
document.getElementsByTagName("body").style.width="950px";
}
if (width >= 1152) {
document.getElementsByTagName("body").style.width="1075px";
}
}
window.onresize = function() {
adjustWidth();
};
window.onload = function() {
adjustWidth();
};
With this script I get an error from Firebug:
document.getElementsByTagName("body").style is undefined
Now my question is, how can i access the style of body? Because in the css sheet its selector and width property are defined.
That function returns a list of nodes, even though there's only one <body>.
document.getElementsByTagName("body")[0].style = ...
Now, that said, you may want to look into doing this with CSS instead of JavaScript. With CSS media queries, you make such adjustments:
#media screen and (max-width: 1151px) {
body { width: 950px; }
}
#media screen and (min-width: 1152px) {
body { width: 1075px; }
}
Media queries work in IE9 and pretty much all other modern browsers. For IE8 you can fall back to JavaScript or just let the body be 100% of the viewport width or something.
document.getElementsByTagName("body")[0].style
document.getElementsByTagName('body')[0].style = 'your code';
Example:
document.getElementsByTagName('body')[0].style = 'margin-top: -70px';
getElementsByTagName returns an array of nodes so you must use [] to access elements.
Try document.getElementsByTagName("body")[0].style
I believe what you get back from document.getElementsByTagName("body") is HTMLCollection. You should be able to use document.getElementsByTagName("body")[0].style to get what you want.
As noted in comments (but strangely still missing among the answers), it should actually be document.body.style. For example, document.body.style.backgroundColor = "#3f3f3f";
For a responsive template, I have a media query in my CSS:
#media screen and (max-width: 960px) {
body{
/* something */
background: red;
}
}
And, I made a jQuery function on resize to log the width:
$(window).resize( function() {
console.log( $(window).width() );
console.log( $(document).width() ); /* same result */
/* something for my js navigation */
}
And there a difference with CSS detection and JS result, I have this meta:
<meta content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width" name="viewport"/>
I suppose it's due to the scrollbar (15 px). How can I do this better?
You're correct about the scroll bar, it's because the CSS is using the device width, but the JS is using the document width.
What you need to do is measure the viewport width in your JS code instead of using the jQuery width function.
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' ] };
}
I found following code on http://www.w3schools.com/js/js_window.asp:
var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
Practically its working the same way as the answer in #Michael Bird's answer, but it's more easy to read.
Edit: I was looking for a method to give exactly the same width as it is used for css media queries. But the suggested one does not work perfect on Safari with scrollbars, sorry. I ended up using modernizr.js in one central function and in the rest of the code I just check if display type is mobile, tablet or desktop. As I am not interested in the width, this works fine for me:
getDisplayType = function () {
if (Modernizr.mq('(min-width: 768px)')){
return 'desktop';
}
else if (Modernizr.mq('(min-width: 480px)')){
return 'tablet'
}
return 'mobile';
};
window.innerWidth is what you need.
if (window.innerWidth < 768) works for 768 break point in CSS
Workaround that always works and is synced with CSS media queries.
Add a div to body
<body>
...
<div class='check-media'></div>
...
</body>
Add style and change them by entering into specific media query
.check-media{
display:none;
width:0;
}
#media screen and (max-width: 768px) {
.check-media{
width:768px;
}
...
}
Then in JS check style that you are changing by entering into media query
if($('.check-media').width() == 768){
console.log('You are in (max-width: 768px)');
}else{
console.log('You are out of (max-width: 768px)');
}
So generally you can check any style that is being changed by entering into specific media query.
My experience was that the media query width tracks document.body.clientWidth. Because of a vertical scroll bar coming and going, checking document, window, or viewport().width could cause my Javascript to run late--after the media query rule change, depending on the height of the window.
Checking document.body.clientWidth allowed my script code to execute consistently at the same time the media query rule took effect.
#media (min-width:873px) {
//some rules
}
...
if ( document.body.clientWidth >= 873) {
// some code
}
The Andy Langton code put me onto this--thanks!
Hi i use this little trick to get JS and CSS work together easily on responsive pages :
Test the visibility of an element displayed or not on CSS #media size condition.
Using bootstrap CSS i test visibility of a hidden-xs class element
var msg = "a message for U";
/* At window load check initial size */
if ( $('#test-xsmall').is(':hidden') ) {
/* This is a CSS Xsmall situation ! */
msg = "#media CSS < 768px. JS width = " + $(window).width() + " red ! ";
$('.redthing-on-xsmall').addClass('redthing').html(msg);
} else {
/* > 768px according to CSS */
msg = "#media CSS > 767px. JS width = " + $(window).width() + " not red ! ";
$('.redthing-on-xsmall').removeClass('redthing').html(msg);
}
/* And again when window resize */
$(window).on('resize', function() {
if ($('#test-xsmall').is(':hidden')) {
msg = "#media CSS < 768px. JS width = " + $(window).width() + " red ! ";
$('.redthing-on-xsmall').addClass('redthing').html(msg);
} else {
msg = "#media CSS > 767px. JS width = " + $(window).width() + " not red ! ";
$('.redthing-on-xsmall').removeClass('redthing').html(msg);
}
});
#media (min-width: 768px) {
.hidden-xs {
display: block !important;
}
}
#media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
.redthing-on-xsmall {
/* need a scrollbar to show window width diff between JS and css */
min-height: 1500px;
}
.redthing {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- the CSS managed Element that is tested by JS -->
<!-- class hidden-xs hides on xsmall screens (bootstrap) -->
<span id="test-xsmall" class="hidden-xs">THIS ELEMENT IS MANAGED BY CSS HIDDEN on #media lower than 767px</span>
<!-- the responsive element managed by Jquery -->
<div class="redthing-on-xsmall">THIS ELEMENT IS MANAGED BY JQUERY RED on #media max width 767px </div>
Css media query is equal to window.innerWidth. Css Media Queries calculate the scrollbar as well.
The simple and reliable way of doing this is to use Media Queries.
To demonstrate, I want to check if the screen width is greater than or equal to 992px (Bootstrap's large device):
function isLargeDevice() {
if (window.matchMedia("(min-width: 992px)").matches) {
return true;
}
return false;
}
If you are using Modernizer then it's a bit easier, here I want to check if the screen is smaller than Bootstrap's large screen (992px)
function isSmallerThanLargeScreen() {
if (Modernizr.mq('(max-width: 991px)')) {
return true;
}
return false;
}
How to use javascript conditionally like CSS3 media queries, orientation?
For Example I can write css for specific
#media only screen and (width : 1024px) and (orientation : landscape) {
.selector1 { width:960px}
}
Now I want to only run some javascript if it match the same conditions
like
#media only screen and (width : 1024px) and (orientation : landscape) {
A javascript code here
}
I have a external javascript for example http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js and it should be only run on specific screen size and orientation
You can use window.matchMedia():
Test a mobile device media query
if (matchMedia('only screen and (max-width: 480px)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
}
Test landscape orientation
if (matchMedia('all and (orientation:landscape)').matches) {
// probably tablet in widescreen view
}
Currently supported in all modern browsers (more details)
Polyfill for old browsers:
https://github.com/paulirish/matchMedia.js/
...I want to run a javascript only if max-width of browser is 1900px
and min-width is 768
EDIT: Actually, that was all wrong. If you're using a mobile device, use:
function doStuff(){
landscape = window.orientation? window.orientation=='landscape' : true;
if(landscape && window.innerWidth<1900 && window.innerWidth > 768){
//code here
}
}
window.onload=window.onresize=doStuff;
if(window.onorientationchange){
window.onorientationchange=doStuff;
}
I can think of a quick solution: Apply some styles conditionally to an invisible div, and check if they are applied with javascript:
div#test { display: none }
#media only screen and (width : 1024px) and (orientation : landscape) {
div#test { background-color: white; }
}
if(document.getElementById('test').style.backgroundColor == 'white')
mediaSelectorIsActive();
It's probably worth mentioning that there is the orientationchange event that you might want to hook into like so:
$('body').bind('orientationchange', function(){
// check orientation, update styles accordingly
});
I know that about this event being fired by mobile Safari, you'd have to check about other browsers.
You could just rewrite the media query as a javascript expression instead:
function sizehandler(evt) {
...
}
function orientationhandler(evt){
// For FF3.6+
if (!evt.gamma && !evt.beta) {
evt.gamma = -(evt.x * (180 / Math.PI));
evt.beta = -(evt.y * (180 / Math.PI));
}
// use evt.gamma, evt.beta, and evt.alpha
// according to dev.w3.org/geo/api/spec-source-orientation
...
}
window.addEventListener('deviceorientation', orientationhandler, false);
window.addEventListener('MozOrientation', orientationhandler, false);
window.addEventListener('load', orientationhandler, false);
window.addEventListener('resize', sizehandler, false);
window.addEventListener('load', sizehandler, false);
The simplest way I found is to get the width of our page; then to conditionally use it.
var x = document.documentElement.clientWidth;
if (x < 992) {
document.body.style.backgroundColor = "yellow";
}