Reputation: 21
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
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
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.
Upvotes: 0