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?

3
  • 1
    define a class/id. set properties of the class/id. Commented Nov 3, 2014 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. Commented Nov 3, 2014 at 16:40
  • Thanks, that clarifies things Commented Nov 3, 2014 at 16:56

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.