Search code examples
javascriptjqueryiosimagedevice-orientation

Dynamically edit img src based on device orientation with JS or JQuery


I am working with an iOS magazine framework (PugPig) which loads HTML documents into a WebKit powered view (a chromeless version of Mobile Safari).

I would like each 'page' to load either a portrait or landscape version of an <img/> depending on the orientation of the device. For various reasons it has to be an <img/> rather than a CSS background image, so media queries won't work. Because I am loading HTML from the local device, no web server stuff can be used either.

So I am guessing that JS is the way to go, but it would need to detect orientation change (or at least screen width) on the fly, without a page refresh, and I don't know if this is possible.

Not hugely familiar with JS hence no sample code (all my attempts so far are car crashes). Sorry.

Any help much appreciated.


Solution

  • OK, found a solution using CSS Media Queries after all, by setting the display property of the img. Bit of a fudge, but fine for now.

    Basically I created two divs, one with a 'landscape' id and another with 'portrait', positioned absolutely on top of each other. Then used @media queries to show/hide the relevant div with the display: property. Very clumsy, not at all suitable for the web but okay for an iPad app loading data straight from memory. And this was before "responsive images" became a thing.