I have an Angular.js application with dynamically background images (should have data-binding for their URL). I also want to use css media queries in order to detect orientation/pixel density etc.
The only solution I found is using javascript to add URL to the background image, something like this:
myDiv.css({'background' : 'url('+ scope.objectData.poster +') no-repeat', 'background-size':'auto 100%'});
This way I have to pass all media queries logic to javascript, something like this. (My intention is to be able to serve different background image for each screen resolution / pixel density / orientation)
I am looking for a cleaner solution to use css media queries and still be able to data-bind my image sources.
tnx!
Yaniv
This is just a starting point solving your problem.
You may use matchMedia: https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia
if (window.matchMedia("(min-width: 400px)").matches) {
$scope.poster = 'small.png';
} else {
$scope.poster = 'big.png';
}
now you can use it in the html file:
<div class="moments-preview-image"
ng-style="{'background-image': 'url('+poster+ ')'}"> ... </div>
If your browser doesn't support this new API you may have a look on some interesting workarounds:
http://wicky.nillia.ms/enquire.js/
http://davidwalsh.name/device-state-detection-css-media-queries-javascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With