Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run javascript/jquery only on screen media, not print

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.

like image 704
Daze Avatar asked Aug 24 '12 15:08

Daze


2 Answers

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();
    }
});
like image 69
Léo Lam Avatar answered Oct 14 '22 03:10

Léo Lam


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

like image 32
mck89 Avatar answered Oct 14 '22 03:10

mck89