ZanQdo
ZanQdo

Reputation: 21

Edit CSS media queries with JS

I need to set the background size via JS. This is my current CSS code that does what I need (set size % seamlessly based on orientation)

background-size: 50%;
@media all and (orientation:landscape) {
    background-size: auto 50%;
}

I would need to change both instances of the 50% value in above's code. Right now I have this

element.css("background-size", foo.toFixed(0) + '%');

This works but discards the media query. How can this be solved?

Upvotes: 2

Views: 169

Answers (2)

Moob
Moob

Reputation: 16184

If you're just checking for orientation changes you could use:

window.addEventListener('orientationchange', doSomethingOnOrientationChange)

but if you actually want to check for media queries being triggered you can use Window.matchMedia() to listen for media query events:

if (matchMedia) {
    var mm = window.matchMedia("(orientation:landscape)");
    mm.addListener(onMatchedMedia);
    onMatchedMedia(mm);
}
function onMatchedMedia(mm) {
    if(mm.matches){
        el.style.backgroundSize = 'auto ' + foo.toFixed(0) + '%';
    } else {
        el.style.backgroundSize = foo.toFixed(0) + '%';
    }
}

Here's a demo using max-width: http://jsfiddle.net/wxgs9g9s/

Upvotes: 1

danhardman
danhardman

Reputation: 621

To add a condition to check whether the window size is landscape, you could use:

if(window.innerHeight < window.innerWidth){
    element.css("background-size", foo.toFixed(0) + '%');
}

If you're using this for mobile development, I'd take a look at the jQuery mobile library.

Source

Upvotes: 0

Related Questions