How to Use JavaScript Conditionally Like CSS3 Media Queries, Orientation

How to write 'responsive javascript' when CSS3 media queries is not available?

Using respond.js together with Modernizr to load it is a simple enough solution. When using Modernizr you don't need to ship the poyfill for most of the Internet (modern browsers), and only load it for the old ones. Example:

Modernizr.load({
test: Modernizr.mq('only all'),
nope: ['respond.js']
});

Basically what respond.js does is add support for media queries to old browsers, so you can write responsive CSS and it will "just work" on old IE.

Using media query to run script only in desktop

That's impossible.
You cannot use a media query to do that (or any CSS in general).

display: none; simply means that the content is not rendered in the browser.

display: none; lets you turn off the display of an element and all descendant elements. But if you take a look at the DOM of the page using the dev tools, the element with display none and his child elements are there in the DOM tree.

So we can conclude that it will not prevent the browser from parsing and then loading that markup and associated resources; your script will be always loaded and your media query and display style won't do anything.

You should check it in your own script if the device is a desktop.
If that script is from a third-party, you should create your own script, check if the device is a desktop, and then load the third-party script if the device is actually a desktop.

Regarding how to detect if a device is a desktop, I'll leave here a couple of answers that have tons of resources to choose from (a device might be either mobile or desktop):

Detecting a mobile browser

What is the best way to detect a mobile device?

Changing Javascript attribute (inline in HTML) based on screensize - like CSS Media Queries

window.resize(function(){
if(screen.width <= 480){
//do something
}else if (screen.width <= 780){
//do something else
}else if(screen.width <= 960){
//do final thing
}
})

You can find more about these hear for resize() and right here for screen.width().

The second link in particular is very instructive for what you are trying to do.

CSS if else conditions, mobile portrait or landscape

You can use the orientation constraint:

@media handheld and (orientation: landscape) {
/* applies to mobiles in landscape mode */
}
@media handheld and (orientation: portrait) {
/* applies to mobiles in portrait mode */
}

Multiple rules are comma separated (OR), otherwise use AND.

See MDN.



Related Topics



Leave a reply



Submit