I looked around and didn't see this question asked yet.
What's a reliable way in Javascript to determine the media type (e.g. screen, print, handheld) of the page? I've seen references to document.styleSheets[0].media
, but I've had no luck using this, either because of browser support issues or because I'm not understanding something.
I'm asking because I want something to be hidden by Javascript in screen view, but not in print view. Media-dependent styles can't be relied on to do this because I'm using Prototype to run a toggle switch for the element, and Prototype won't allow an element to be switched to visible if it was declared invisible (display: none
) with non-inline CSS*. I tried to just set media-specific inline styles for the element (<div style="@media print { foo: bar; } @media screen { blargh: bfargle; }">
), but from what I can tell, that's not supported.
I know that I can cycle through the stylesheets and check to see if a print-specific linked stylesheet is active or not, but I'm currently in a situation where various media-specific style declarations are all mixed around in a single linked stylesheet, so that's no good. And yeah, I can just split up the stylesheets into different media types, but I'd first like to figure out whether or not I can just reliably pull the media type out of the DOM with Javascript, completely independently of CSS. Oh, and I've tried that trick of "hide an element for the print view, then check to see if it's visible with Javascript" but that's always resulted in (when I load up print preview) Javascript detemining that the supposed-to-be-hidden elements are visible and performing whatever DOM manipulation I tell it to, despite the fact that those elements aren't visible. If anybody would like more details about what I'm talking about here, I can elaborate in an edit.
*This is something that I haven't understood and am constantly irritated by. Anyone that can provide any insight into it gets a big upvote from me.