In Javascript is there a direct way (not involving parsing the css code) to determine which media query is active?
For instance I have two queries:
#media screen and (max-width:800px)
#media screen and (min-width:801px)
without parsing and looking at the clientWidth, how can I tell which one of these has evaluated to true.
Though this is an old question it ranks highly when googling for this problem.
Window.matchMedia is official and is supported by all major browsers (IE10+) and will allow you to query if a certain media query currently matches.
From the original question:
if (window.matchMedia('screen and (max-width:800px)').matches) {
// it matches
} else {
// does not match
}
You can also listen for when the query match result changes by attaching an event listener to the MediaQueryList that window.matchMedia returns:
var mql = window.matchMedia('screen and (max-width:800px)');
mql.addEventListener(
function(mq) {
if (mq.matches) {
// it matches
} else {
// does not match
}
}
);
Paul Irish's MatchMedia may do the trick:
https://github.com/paulirish/matchMedia.js
Would that suit what you are trying to do?
To see how different media queries react on resize or orientation change, try the demo on this page:
http://www.jensbits.com/2011/04/20/media-query-playground-rotate-resize-rinse-repeat/
You can adjust the media query attributes to get a feel for how they affect a page.
Hi and i hope this helps, am actually adding a class to a selector and i am working with this tool: https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/
in fact, they have a clear example of what is turn on within the resized window here
http://robnyman.github.io/matchmedia/
in my case am just doing specific task when am on a specific size that you can get using the function.
I'm not sure how would you know which media-query is active, but...
...can't you just check the screen width with javascript?
if ( window.innerWidth >= 801 ) {
// #media screen and (min-width:801px)
} else {
// #media screen and (max-width:800px
}
or, what am i missing here?
Related
Foundation has some JS functions to detect Media Queries. My question is how to define some functions just Firing in Medium-up media queries?
Exactly I want to firing Foundation Equalizer on medium-up or actually stop working on Mobile.
Thanks :)
#parhum,
I am not sure if this is the right approach but you can always remove the data-equalizer attribute and add it back on.
// media query event handler
if (matchMedia) {
var mq = window.matchMedia("(min-width: 767px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
// window width is at least 767px
$('.row').attr('data-equalizer','data-equalizer');
}
else {
// window width is less than 767px
$('.row').removeAttr('data-equalizer');
}
}
For some reason, I was not able to get this working
Foundation.utils.register_media('custom', "(min-width: 767px)");
if (matchMedia(Foundation.media_queries['custom']).matches) {
// window width is at least 767px
$('.row').attr('data-equalizer', 'data-equalizer');
} else {
// window width is less than 767px
$('.row').removeAttr('data-equalizer');
}
Preview : #Fiddle | Code : #Editor
~Arvind
Foundation 6 supports a Equalizer property called "equalizeOn", which lets you set a breakpoint. Equalizer will do it's stuff to this breakpoint and up (Mobile First Approach).
Here's a link to the docs (Section, Plugin Options):
http://foundation.zurb.com/sites/docs/equalizer.html
You can set the option via data attributes in your HTML or via JavaScript.
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 have a jquery funciton which sticks the navbar to the top of the webpage, but I only want this feature in desktop and tablet mode (not in phone mode). How do I de-activate this function?
$(document).scroll(function(){
var elem = $('.navbar');
if (!elem.attr('data-top')) {
if (elem.hasClass('navbar-fixed-top'))
return;
var offset = elem.offset()
elem.attr('data-top', offset.top);
}
if (elem.attr('data-top') <= $(this).scrollTop() )
elem.addClass('navbar-fixed-top');
else
elem.removeClass('navbar-fixed-top');
});
Use CSS media queries to manipulate the nav bar. Browser/OS detection shouldn't factor into styling, just resolution and media type.
What is the syntax for a CSS media query that applies to more than one property (AND operator)?
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries
Based on your question, it seems like the real concern here is saving screen real estate on a mobile device. So as most of the other users have pointed out, you can rely on using media queries here instead. In order to make sure the listener isn't even attached in case of small screens, you can use Modernizr.mq to test a media query and use the returned value:
if( Modernizr.mq('only screen and (min-height: 640px)') ) {
// Case specific code here, only executed if screen height is > 640px
}
This is assuming you're willing to add Modernizr or are already using it. If you don't have it already included and only plan on using this single test, you can download a custom build(2kB) from modernizr.com which only includes the media query test.
Check this out -- It maybe what you're looking for they're Open source mobile phone detection
http://detectmobilebrowsers.com/
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