10

How can I run a jquery function only on @media screen?

Background:

I have a screen.css stylesheet and a print.css stylesheet. I have two javascript functions, one of which I do not want to run on the printed version want of the page.

1
  • Just to clarify: I'm printing to PDF, as I currently don't have access to a physical printer. Nevertheless, I need this to apply to both hardcopies and PDF printouts.
    – Daze
    Aug 24, 2012 at 16:43

3 Answers 3

9

Any script would be ran when the page loads, so using if (Modernizr.mq('only screen')) {$('h1').text('media screen');} is pointless as it runs your script while you're on @media screen.

Instead, you have to detect whenever the media query changes, and change the page accordingly. You could use something like enquire.js to do so easily:

// This is just an example, be more creative!

enquire.register("screen", {
    match: function() { 
        $('#only-show-on-screen').show();
    },
    unmatch: function() {
        $('#only-show-on-screen').hide();
    }
});
2
  • 1
    This is the real answer. All the other answers (to date) are expecting the page to be reloaded on print, but it is not. Any DOM changes made for the screen version persist on the print version. Feb 28, 2014 at 22:24
  • I've updated my answer to make it clearer and how this could be done with enquire.js.
    – Léo Lam
    Mar 1, 2014 at 10:17
5

In latest browsers you can use matchesMedia:

if (window.matchMedia("screen").matches) {
    ....
}

If you want to support older browsers too you can use a polyfill like matchMedia.js

1
  • 2
    Elegant, however, my script still seems to also apply to print (print to PDF). Using Chrome 21, Firefox 11, Safari 6 on Mac.
    – Daze
    Aug 24, 2012 at 15:44
0

I think you could use Modernizr. Although, there must be a native way to do it in javascript.

http://modernizr.com/docs/#mq

I have never tried it but it is something like this:

if (Modernizr.mq('only screen'))
{
..
}

beware with old browsers not supporting media queries.

4
  • Thanks, I tried your suggestion, but my script still seems to also apply to print (print to PDF). Using Chrome 21, Firefox 11, Safari 6 on Mac.
    – Daze
    Aug 24, 2012 at 15:45
  • Are you saying that this: Modernizr.mq('only screen') returned true and executed your code before printing? Aug 24, 2012 at 15:51
  • Yes, if (Modernizr.mq('only screen')) {$('h1').text('media screen');} gives me "media screen" in both browser viewport and PDF printout.
    – Daze
    Aug 24, 2012 at 15:55
  • Actually, I don't think it returned true. What class would it give my <html> tag?
    – Daze
    Aug 24, 2012 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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