Krzysztof Abramowicz
Krzysztof Abramowicz

Reputation: 1616

How to react on style changes within a Web page?

Lets assume that we have a responsively-designed Web page which uses media queries to achieve three different views: screen, handheld and print. Lets assume further, that such a Web page includes several JS-based, view-dependent layout fixes, navigation logic, content-generating macros and similar stuff, reason for which may be more or less controversial.

Now, please imagine that users are playing with our design by resizing browser window and printing it's contents. A we would like to react on the style changes (carried out by the browser) in order to recalculate layout fixes, regenerate dynamic content, rearrange navigation or whatever else. But there is no "onMediaChange" event to be handled by our script, is it? So, in what way could a Web developer synchronise the media-driven style with the media-independent logic?

This question, in several forms and development contexts, has been asked on StackOverlow for years, but no rewarding answer has been given yet. There are workaroundss using width-based conditionals, but these neither handle the print view, nor react to width changes occurring after the page has loaded. Other group of CSS-sniffing solutions is based on polling which is fallible and inelegant. What I am looking for is a general, elegant, standards-compliant, client-side solution for synchronising JS and CSS with media changes. Two non-existing, ideal solutions could be:

  1. The existence of an onMediaChange event, e.g.:

    document.addEventListener('onMediaChange', myHandler, false);
    
  2. The possibility to attach scripts with the link tag, e.g.:

    <link rel="script" media="print" type="text/javascript" href="print.js"/>
    

I'll be grateful for any existing solutions, creative suggestions, theoretical comments or even a philosophical discussion exceeding the scope of this question.

Upvotes: 2

Views: 354

Answers (1)

skz
skz

Reputation: 165

I think you're looking for window.matchMedia API:

https://developer.mozilla.org/en-US/docs/DOM/window.matchMedia

Basically, it'll let you attach an Event Listener to media queries. You could pair this with an append() method to add/remove dinamically <link> tags.

Unfortunately, as far as I know, it is poorly supported among old browsers, but using a polyfill (like this one) you could potentially get a global, cross-browser support.

Upvotes: 1

Related Questions