Can I use JavaScript to get the dimensions that media queries use? - javascript

For example here is a fiddle which shows how to change a font when the width drops below 200px.
#media (max-width: 200px) {
.test {
font-size:40px;
}
}
If you move the html window to the right to make it smaller you will see the point at which it hits 200px b.c. the font will change.
If someone could add a dynamic div to the fiddle so that this value would be output to the window this would be a cool test script for media queries.
Also, if there is a good reference on the web for the JavaScript interface to media queries. I hope there is one. I have not found it yet.

You can add an event listener to window.matchMedia
if (matchMedia) {
var mq = window.matchMedia("(max-width: 200px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
console.log('matches')
}
}
Demo

I did using jQuery, hope this helps.
$( window ).resize(function() {
if($(window).width()<=200){
$(".test").css("font-size","40px");
}
else{
$(".test").css("font-size","20px");
} });
http://jsfiddle.net/7gup43rx/2/

Here is what you were actually asking for. The snippet below will output the dimensions that media query uses.
http://jsfiddle.net/jbnt7nh1/8/
// some code - updated fiddle
Here is a good point to start reading about the different widths in CSS.
https://www.google.com/#q=quirksmode+screen+width

Related

Javascript code hiding a div doesn't work (CSS #media rule doesn't work either)- 'cannot read property style of null'

So, I've got a button that display toggles a div on a click event. It works properly. However, I can't hide the same div using nearly the same code (however, I want to toggle this div after my screen becomes too big, not after clicking), because I get the problem like in the title- 'cannot read property style of null'
The part that doesn't work (hiding a div after screen becomes too big:
if (screen.width > 900) {
document.getElementById('klik').style.display = 'none';
}
And the part that works (button toggles a div using a click event):
function showDiv() {
if (document.getElementById('klik').style.display == 'block'){
document.getElementById('klik').style.display = 'none';
}
else{
document.getElementById('klik').style.display = 'block';
}
}
I wrote this code because I want to do a scalable menu, displaying a div with list items inside after clicking on it. The menu button is visible only when screen-width <= 900px, if screen-width > 900px I've got a normal navigation bar and the button disappears.
Am I forgetting something? I'm new to Javascript. Also one more thing- it also doesn't work using #media rule, however I can change the background-color with #media. I hope it might help. Also thanks in advance.
Note Two Problems:
Ensure that the element you want to change it's display has the id="klik"
The below code will execute only once.
if (screen.width > 900) { document.getElementById('klik').style.display = 'none'; }
But why?
The answer is because you didn't set an event to run it every time when your resize the screen. Also, screen.width will always return the width of the display. What you are looking for is the window.innerWidth
So a possible solution:
window.addEventListener('resize', function(){
document.getElementById("screen").innerHTML = window.innerWidth.toString() + "px";
if(window.innerWidth < 900)
{
//Perform your desired Executions Here
}
});
<div id="screen"></div>
This will run the code every time a window.onresize is triggered. And that's exactly what #media in CSS does. It works on window.onresize behind the scene in javascript sense.
Note: I have added a simple illustration on how to work with screen.resize which you can use as the basis for modifying element properties based on a certain range. All you need to do, is to ensure that you do your styling within that block and it will work.
Hmmm, actually this is exactly what media queries are made for. Did you try
#media (min-width: 900px) {
#klik {
display: none;
}
}
If that doesn't work: Are there any other css styles that may overwrite that particular style? Something like #klik { display: block !important; } ...?

Conditional Media Queries window.matchMedia

I am working with window.matchMedia(), and I cannot seem to get the function to apply a secondary class when a max or min width is reached. I've recreated the problem below with a simple font-size change.
I've read up on matchMedia() and I've tried this two different ways (both are included below). Do I need to include both a min and max value in order to have the function execute? Or am I missing something within the actual structure of the function itself?
$(document).ready(function() {
var mq = window.matchMedia('(max-width: 700px)');
if( mq.matches ) {
$('.title').addClass('big')
} else {
$('.title').removeClass('big');
}
});
/*
Second method I tried
$(function() {
if( window.matchMedia('(max-width: 700px)').matches){
$('.title').addClass('big')
} else {
$('.title').removeClass('big');
}
});
*/
.title {
font-size: 20px;
}
.big {
font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="title">This is a title</h1>
It is working, maybe you are expecting it to detect screen resize?
You have it bound to document.ready() so you have to refresh the page to see it.
Try it out:
Make windows smaller than 700px, refresh
make window larger then 700px, refresh
Notice difference :)
In another words:
$(document).ready(your function)
Your function only executes once for each time page is loaded.
Alternatively, use this fiddle and run it. Make result window larger or smaller than 700px and run it again.
If you need to run it every time when window width resizes I would recommend binding to window.onresize as I did in this fiddle with execution on resize event
Notice the console.log I put there for you to see how and when it is triggered, you wanna remove it before going production ;)

Completely remove a div if screen width is less than 800 (mobile device)

So i've been looking around and i can't really find i good solution on this so i hope some of you could help me out...
I am trying to remove a div so it doesn't exist if my screen size is around the size of a mobile... I know there is display none which makes the div invisible but since i got a setInterval function on that div it stil load each 5 second... So my question is:
Can i remove a div completely if my screen is less than x pixels
or is it possible to only run my setinterval function when the width is more than x?
Thanks for your time!
setInterval(function(){
$( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);
this is a naive implementation, the setinterval runs anyway and checks if it must "operate", the div is hidden under a certain window width, you can modify this logic by clearing and restarting the interval on desidered width, inside the resize function handler, and debouncing the resize event.
function isMobilewidth () {
return $(window).width() <= 800;
}
$(window).on('resize', function() {
$('.chatMessages').toggle(isMobilewidth());
});
setInterval(function(){
if (!isMobilewidth())
$( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);
You can use CSS media queries:
#media only screen and (max-width: 800px) {
div {
display: none;
}
}
If you want to stick with javascript, try the .offsetWidth property of DOM elements
Use CSS #media rules:
#media (max-width: 800px) {
.div {
display:none;
}
}​
https://fiddle.jshell.net/Luc2zrbd/
In this case, you can get the device's screen width as shown below and do your operations accordingly.
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
you may not need a setInterval, you can base your test on a window.resize which is triggered also on page load on device mobiles
See here for an explanation of mobile viewports:
http://www.quirksmode.org/mobile/viewports2.html
window.onresize = function(){
// set your business here
}

Remove div/iframe on certain width

I want to make my site mobile friendly but I run into one problem.
I have an player of a streaming plattform on my main page, which is invisible/hidden on a certain width by using media queries in CSS, but it still gets loaded.
I want to remove this container/iframe completly for any width lower than 1280px or 768px.
I've tried to fiddle around with jquery/javascript a bit but it's not working for me and I need some help :D
This is what I tried to use:
$(window).resize(function() {
if ($(window).width() < 1280) {
$(container_selector).document.getElementById("video-container"){
this.pause();
delete(this);
$(this).remove();
});
$(container_selector).empty();
}
});
This is the container/iframe I want to remove:
<div id="video-container"><iframe src="http://www.hitbox.tv/embed/kazuto" width="300" height="150" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div>
Thanks in advance :)
You can use media queries.
For instance, like this:
#media (max-width: 1280px) {
#video-container {
display: none;
}
}
Here is the code to remove the whole div and the iframe inside.
$(window).resize(function () {
if ($(this).width() < 1280) {
$("#video-container").remove();
}
});
But since you trigger it on resize, what's when the window width increases again? If you just want to hide the iframe on lower resolutions and show it again when user resizes back to higher resolution, then I would recommend to use hide() and show() (or use the answer proposed by #Sergey Kopyrin)
Code sample
$(window).resize(function () {
if ($(this).width() < 1280) {
$("#video-container").hide();
} else{
$("#video-container").show();
}
});
You can also specify a duration parameter inside those methods (e.g. $("#video-container").hide(500) ) so it will not be hidden abruptly.

Jquery, Remove class when width screen is 1050px

This is the JS code i'm using:
$("document").ready(function($){
var nav = $('#menu2');
$(window).scroll(function () {
if ($(this).scrollTop() > 90) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
});
But i can't seem to get this into my code.
function checkWidth(init){
/*If browser resized, check width again */
if ($(window).width() < 514) {
$('html').addClass('mobile');
}
else {
if (!init) {
$('html').removeClass('mobile');
}}}$(document).ready(function() {
checkWidth(true);
$(window).resize(function() {
checkWidth(false);
});
And what i want is that when .f-nav is added to #menu2, when the screen is <1050 the classshould be removed.
To change html to #menu2, just replace one with the other. jQuery is pretty simple in this respect
if ($(window).width() < 514) {
$('#menu2').addClass('f-nav');
} else {
$('#menu2').removeClass('f-nav');
}
JSFiddle
There are a few ways to do that:
Javascript only
See it in action: Fiddle
$(window).resize(function() {
if ($(window).width() < 1050) {
$selector.removeClass('my-class');
} else {
$selector.addClass('my-class');
}
}).resize(); // trigger resize event initially
And don't forget: You don't have to place $(window).resize inside $(document).ready.
Mixed Javascript & CSS
See it in action: Fiddle
This technique is explained here: http://www.senaeh.de/media-query-variablen-javascript-auslesen/
Basic principle: set a variable with a CSS pseudo element and get it with javascript.
This workaround is good if you have to use Javascript even if media queries are used, because you don't have to declare the breakpoint twice.
CSS
#media screen and (max-width: 1050px) {
body:after {
content: 'tablet';
display: none;
}
}
Javascript
var mode = window.getComputedStyle(document.body,':after').getPropertyValue('content');
Be aware: IE < 9 doesn't support getComputedStyle. You have to use a polyfill like this one.
this is best achieved with a media query
#media screen and (max-width:1050px){
.mobile{
/* will only apply on devices narrower than 1050px */
}
}
EDIT: also possible to use media queries with javascript in modern browsers
if (matchMedia) { // check if browser supports media queries from JavaScript
var mq = window.matchMedia("(max-width: 1050px)");
WidthChange(mq);
// every time width changes, check the media query
mq.addListener(function WidthChange(mq){
if(mq.matches){
//we are in a mobile size browser
$('#menu2').addClass('mobile');
$('#menu2').removeClass('f-nav');
} else{
// desktop browser
$('#menu2').addClass('f-nav');
$('#menu2').removeClass('mobile');
}
});
}
When you load a website on a screen bigger than your breakpoint, the script wont work, because you need to re-calculate the screen size(refresh the page in this case). You need to get the width of the screen on resize. Use resize() method, and inside it place your test condition, and assign the class to your element. Reference to help you: http://api.jquery.com/resize/
If you want to change the class of a div in JS, you can do something like that:
document.getElementById("#YourId").className = "YourNewClass"
It will just change your class attribute :-)
Like that, you can also check which class is used and do what you want to do with that.
Edit thanks to Olaf Dietsche: this must be a duplicated post, here can be your answer: jquery, add/remove class when window width changes

Categories

Resources