2

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?

ZanQdo
  • 21
  • 2
  • 1
    define a class/id. set properties of the class/id. – oshell Nov 03 '14 at 16:39
  • 1
    It is impossible to do this with jQuery's `css` function, because it works by setting inline `style` properties. [Media queries don't work with inline styles.](http://stackoverflow.com/questions/9808233/is-it-possible-to-put-css-media-rules-inline) – lonesomeday Nov 03 '14 at 16:40
  • Thanks, that clarifies things – ZanQdo Nov 03 '14 at 16:56

2 Answers2

1

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/

Moob
  • 14,420
  • 1
  • 34
  • 47
0

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

Community
  • 1
  • 1
danhardman
  • 633
  • 1
  • 6
  • 16