Detecting media queries via javascript and apply appropriate data-state - javascript

I need javascript #help.
I have an object(#objID) with three different data state (A B & C) (https://www.dropbox.com/s/zn19k87eu2hp8ow/data-states.jpg?dl=0)... Each state contain some css to describe the look of it..
I want to use javascript to detect media queries change and add the appropriate data state to #objID.
(ie.
if screen is under 320px then add [data-state="A"] to #objID
or if screen is between 320px and 728px then switch to [data-state="B"]
or if screen is above 1024px then switch to [data-state="C"]
)
similar to this concept..http://zerosixthree.se/detecting-media-queries-with-javascript/
but im not sure how to implement it.
Please help. Thanks

To simplify you can do something like this:
window.matchMedia("(max-width: 320px)").addListener(function() {
// Change the value of `data-state`
});
window.matchMedia("(min-width: 321px) and (max-width: 728px)").addListener(function() {
// Change the value of `data-state`
});
However you need make sure the browser supports window.matchMedia and also handles maintaining state etc to know when you've crossed from one breakpoint and into the other and identify which is active as both will trigger as you exit and enter breakpoints.
As for doing it on window.onresize this is not a very performant way to do this and you must throttle/debounce if you do it that way. Using matchMedia will only trigger when the breakpoint changes rather than continuously on resize. It also give you the benefit of keeping your CSS media breakpoints in sync with your JS.
This is a Polyfill for browsers which do not support it as mentioned and this guide might also help you.
However:
I have an object(#objID) with three different data state (A B & C).
Each state contain some css to describe the look of it..
Sounds as though you want to change the CSS styles applied to an element based on the data-state attribute, which you are going to change per breakpoint?
Correct me if I am wrong but why can't you just use media queries to change the CSS that is applied to it instead?
#media only screen and (max-width: 320px) {
/* State A */
.css-selector {
color: red;
}
}
#media only screen and (min-width: 321px) and (max-width: 728px) {
/* State B */
.css-selector {
color: green;
}
}
#media only screen and (min-width: 728px) {
/* State C */
.css-selector {
color: blue;
}
}

You need the onresize event
window.onresize = function(event) {
//...
};
The screen has two dimensions, width and height, and you describe a one-dimensional comparison, which does not give us enough information about what you want to achieve. Anyway, you can use window.innerWidth and window.innerHeight inside your onresize event.

Related

Use hover/active CSS by default on mobile devices

On desktop devices, I have designed my elements to be grayed out by default, but become colored when a user hovers over them. On mobile devices, I want them to use the hover state CSS to be colored in by default. Is it possible to do this through JavaScript?
I have lots of elements with different colors, so it would be much easier to simply trigger the state through JavaScript rather than writing new classes and adding them to the elements.
No need for JS! You can use media queries in CSS to accomplish this.
Note: I'm using Bootstrap 4's numbers for screen sizes in this example:
.element:hover {
background-color: gray
}
#media only screen and (max-width: 767px) {
.element {
background-color: gray;
}
}
Bootstrap starts medium screen sizes at 768px, hence my max width of 767. If you want, you can try it out at https://jsfiddle.net/21haxstd/

Changing Margins Depending on Browser Width Javascript

Im trying to make an "Additional Comments" box on my website, which floats to the right of the page, while there's 4 inputs on the right.
For some reason, the comments box, on browser resizing, sits behind the inputs.
I want to make it so that when the browser is less than, say for example, 400px, it applies a margin to the comments box. I tried the below, but that didn't seem to work.
var browserSize = window.innerWidth();
var additional = document.getElementById("additional");
if(browserSize < 400px) {
additional.style.marginTop = "200px";
}
Could someone guide me as to where to go?
Many thanks in advance!
Why not use CSS media queries? You can do something like this in a stylesheet:
#media only screen and (max-width: 400px) {
#additional {
margin-top: 200px;
}
}
However, you should try to avoid using IDs as CSS selectors as much as possible.
Add an event listener for browser resize and a function for your work inside it:
function processResize()
{
var browserSize = window.innerWidth();
var additional = document.getElementById("additional");
if(browserSize < 400px) {
additional.style.marginTop = "200px";
}
}
window.addEventListener("resize", processResize);

Stop being responsive at a certain width

I know this question sounds crazy, but I'm going to explain it.
I have a responsive website and all works OK, but when the width is too low (width < 500px) the website (which is still responsive) start to rearrange in such a way that I prefer to NOT being responsive anymore.
I'd like to know if there is a script or anything that can solve this. Please any help will be useful :)
set a minimum width on the html / body
html, body {
min-width: 500px;
}
Making elements responsive is usually done by setting width to a percentage of parent elements. The above would be an easy fix, but it's possible there will be elements you need to style using media queries.
You can place your css within media queries so that it only applies under particular conditions. E.g.
#media only screen and (max-width: 500px) {
body {
background-color: lightblue;
}
}

How does the CSS mediaQuery works

I need to know how the CSS media query works.
I mean, if I use #media(min-width: 768px), does this function called every time the window is resized ?
Because I am wondering if I can use a Javascript $(window).bind('resize orientationchange') or if it is more resource intensive.
It is for add or remove a class to a div, an exemple :
http://jsfiddle.net/xbh28o08/
My goal is to enter in the HTML a data attribut which determine when the navbar has to collapse (data-breakpoint"768" for example). And I would get this breakpoint for make a responsive navbar automatically, without change any CSS. My idea was to do it with Javascript but it seems really not a good idea according to your answers
var widthScreen = $(window).width();
if (widthScreen > 768)
$('nav').addClass('large');
else
$('nav').addClass('small');
$(window).bind('resize orientationchange', function() {
widthScreen = $(window).width();
if (widthScreen > 768){
$('nav').addClass('large');
$('nav').removeClass('small');
}
else{
$('nav').removeClass('large');
$('nav').addClass('small');
}
});
to answer your first question: yes a media query does get called every time you do resize the window.
there is no need to add classes with javascript, I provided you with an example:
it does completely the same but no js needed. Its better to avoid using javascript when its not needed.
nav{
background: green;
}
#media(min-width: 768px){
nav{
background: red;
}
}
<nav>
<ul>
<li>Link 1</li>
<li>Link 2</li>
</ul>
</nav>
I suggest you use css media queries instead of javascript as css is faster than javascript
As soon as Your device width is 768px all the css in that will be called and would overwrite the any other if exist
For more info you can check the link below
Css Media Queries
A CSS media query will apply whenever the conditions in it are fulfilled (for instance, media screen and max-width of 768px), and be ignored whenever it is not. It applies to the window size and will update on resize. You can test this on this website by shrinking your browser.
Such a use-case (using the window resize event) is not recommended as it will trigger on every resize event. Not just when the resizing is finished, but also every tick between start and end. The only use case I know of is to add/remove classes, which is both not recommended, and also a downright CPU hog.
Media query will trigger only when particular point (width or height) mentioned in your media query, whereas javascript resize will trigger at every pixel changed during resize. And, JS is more resource intensive IMO whereas CSS is not and faster. Have a read here
So, in your case, instead of removing and adding classes, have one class and override it's properties based on the screen size in your media query. Something like:
.my-class { width: 400px; }
#media(min-width: 768px){
.my-class { width: 200px; }
}
OR
You can have 2 classes all the time, but only one will take effect based on the screen size. This way you don't override properties (which is a bit ugly, but, that's just me)
// screen <= 767
#media(max-width: 767px){
.nav-small {
width: 320px;
}
}
// screen >= 768
#media(min-width: 768px){
.nav-large {
width: 100%;
}
}

jQuery - If screen is less than specified width (responsive)

How can I make an alert popup if the width of the page is less than 1200px, and made responsive?
Thanks!
You can use something like the breakpoints module. Then you setup a breakpoint to trigger at 1200px and show a dialog and either add a css class that changes the layout, or use straight javascript to make the changes.
breakpoints(1200, function(oldPoint, newPoint) {
alert('The screen width just changed');
});
if you just wanted native jQuery:
$(window).resize(function() {
var width = $(window).width();
if (width < 1200){
alert('Your screen is too small');
}
});
For completeness, heres the CSS media query (still doesn't take care of the alert, but can help with making the website "responsive").
/* some normal style */
.myclass {
font-size: 22pt;
}
/* alter the style when the screen's smaller */
#media screen and (max-width: 1200px) {
.myclass {
font-size: 18pt;
}
}
For future Googlers, a 2019 solution is to use JavaScript's window​.match​Media(). It is supported in all major browsers and IE 10 onwards.
You can use it like this:
if (window.matchMedia('(max-width: 1200px)').matches) {
// functionality for screens smaller than 1200px
}
To make this responsive, you just need to wrap it in a resize function:
$(window).resize(function() {
if (window.matchMedia('(max-width: 1200px)').matches) {
// functionality for screens smaller than 1200px
}
});
This is arguably the most easiest way to check a screen size and it doesn't bloat the code.
Check the Mozilla docs about match​Media to learn more and this one for more info on Testing media queries programmatically.

Categories