Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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

share|improve this answer
    
The matchMedia solution works great for me (I'm developing for mobile devices). Tnx! –  Yaniv Jan 9 at 8:34
    
@Yaniv How about Windows Phone devices? MDN says that IE Mobile isn't supported –  mykola.rykov Jun 15 at 20:41
    
Oh - might be... I'm only developing for iOS & Android devices. What about using a Polyfill? Did you look for one? (for example: github.com/paulirish/matchMedia.js). Good luck! –  Yaniv 2 days ago
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.