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.
Related
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.
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/
Hi I wanted to know using jQuery or javascript can I remove a certain div tag so that its not displayed at all when the screen gets to a certain size lets say 500px.
You should use the matchMedia Javascript API, which has a very good support across browsers nowadays.
For instance:
var width = window.matchMedia('screen and (width: 500px)');
matchMedia will return a MediaQueryList object, which among other things contains a matches boolean that indicates if the passed in media query currently matches or not.
The great thing about those MediaQueryList objects is, that they provide methods to add and remove listeners, when this state changes.
For instance:
width.addListener(function( mql ) {
if( mql.matches ) {
// yes, the device screen width is now 500 pixels
} else {
// no, the width is below 500 pixels
}
});
You can write something like this in jQuery
$(document).ready(function(){
$(window).resize(function(){
if($(window).width()==500)
$('div').hide();
else
$('div').show();
});
});
You can do this using CSS media queries:
#media screen and (min-width: 500px) {
div.whatever { display: none; }
}
I'm trying to figure out how I can optionally run a block of javascript based on the current device/media query. I'm using Twitter Bootstrap and have essentially two versions of media queries:
#media (min-width: 980px) { ... } <!-- Desktops -->
#media (max-width: 979px) { ... } <!-- Smaller screens/tablets/phones -->
I have a map that I generate, but am not showing it in the mobile/small screen version forb andwidth reasons. Yet, the javascript still executes in the background even though you can't see it on the mobile screen. So, I'm trying to find a way in javascript where I can do something like:
// Imaginary function
var screenType = getScreenType();
if(screenType == 1) {
// Load map
}
I've read about people setting CSS properties to specific values in their media queries and then trying to find that element in the DOM based on the CSS property, but there has got to be a better way. Any ideas?
The current accepted answer is not good enough, you should check window.matchMedia
You can detect viewport dimension changes, but you must calculate factors such as orientation and aspect ratios and there is no guarantee our calculation will match our browser assumptions when it applies media query rules.
I mean, you can calculate X, but your browser assumption can be Y.
So i think is better to use same browser rules, and window.matchMedia does it
var jmediaquery = window.matchMedia( "(min-width: 480px)" )
if (jmediaquery.matches) {
// window width is at least 480px
}
else {
// window width is less than 480px
}
You can even receive query notification using a listener
var jmediaquery = window.matchMedia("(orientation: portrait)");
jmediaquery.addListener(handleOrientationChange);
handleOrientationChange(jmediaquery);
function handleOrientationChange(jmediaquery) {
if (jmediaquery.matches) {
// orientation changed
}
}
If you no longer need to receive notifications about changes simply call removeListener()
jmediaquery.removeListener(handleOrientationChange);
You might find the Enquire.js library helpful:
http://wickynilliams.github.com/enquire.js/
CSS-Tricks article: http://css-tricks.com/enquire-js-media-query-callbacks-in-javascript/
How about using javascript for that?
<script type="text/javascript">
if (screen.width < 980) {
document.write('<link href="UrLowRes.css" type="text/css" rel="stylesheet"/>');
} else {
document.write('<link href="UrlHighRes.css" type="text/css" rel="stylesheet"/>');
}
</script>
You can also using a plugin called minwidth:
minwidth(940, function () {
//do whatever you need
});
But it only works when the page loads not when resizing..
http://edenspiekermann.com/en/blog/responsive-javascript-helpers
I have two images "image-big.jpg" and "image-small.jpg" I want to via javascript detect if screen width <= 699 and change the SRC of my image with class="imageswap" from image-big.jpg to image-small.jpg.
So basically if they are on a portable device it will display the smaller image.
I am novice at best with javascsript and any help is gratefully appreciated!
Bind to the window onresize event:
window.onresize = function(event) {
if(window.innerWidth && window.innerWidth===699)
document.getElementById('myImg').src = 'newSource';
else if(document.body.offsetWidth && document.body.offsetWidth===669)
document.getElementById('myImg').src = 'newSource';
};
The else if is for IE < v.9
Its no in specs but screen works fine in all browsers.
if(screen.width <= 699){
// do you logic
}
1st approach: client-side. Set classname to html tag on dom ready after detection device type. Use css:
html.big .image-div {background-image:url('big.jpg')}
html.small .image-div {background-image:url('small.jpg')}
2nd approach: redirect. Use 2 different URLs and redirect for small size by detection User-Agent. It's better to use User-Agent (navigator object) than window/screen width
Usually I preffer redirects, because you have better code and page look when you can customize it for specific device. It's the way how leaders behave.
Try media-query.
.imageswap{
background-image:url('small.jpg');
}
#media screen and (max-width: 699px) {
background-image:url('small.jpg');
}