JS MatchMedia

Toggle class name on click in jQuery

by Nicolas AGUENOT

HTML

<div id="message">
  Resize your screen !
  <div id="orientation"></div>
  <div id="size"></div>
</div>

CSS

body {
  background: #0c687e;
  padding: 20px;
  font-family: Abril Fatface;
}

#message {
  background: #fff;
  border-radius: 4px;
  padding:50px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
}
#size,
#orientation
{
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  color:#fff;
  text-align: center;
  transition: all 0.2s;
  margin: 40px auto 0px;
  
}
#orientation {
  background: #2a92ac;
}

#size {
  background: #0c687e;

}

JavaScript

// Déclaration des matches
var portraitLandscape = window.matchMedia("(orientation: landscape)");
var mobile = window.matchMedia("(max-width: 768px)");
var tabletPortrait = window.matchMedia("(max-width: 991px)");
var tabletLandscape = window.matchMedia("(max-width: 1199px)");

if (portraitLandscape.matches) {
    $("#orientation").text('Loaded to landscape');
} else {
    $("#orientation").text('Loaded to portrait');
}

if (mobile.matches) {
    // Loaded to Mobile format
    $("#size").text('Loaded to mobile');
}
if (tabletPortrait.matches) {
    // Loaded to tabletPortrait format
    $("#size").text('Loaded to tabletPortrait');
}
if (tabletLandscape.matches) {
    // Loaded to tabletLandscape format
    $("#size").text('Loaded to tabletLandscape');
} else {
    // Loaded to greater than 1199px
    $("#size").text('Loaded to greater than 1199px');
}

// Manage orientation
portraitLandscape.addListener(function(m) {
    if (m.matches) {
        // Changed to landscape
        $("#orientation").text('Loaded to landscape');
    } else {
        // Changed to portrait
        $("#orientation").text('Loaded to portrait');
    }
});
// Manage mobile
mobile.addListener(function(m) {
    if (m.matches) {
        // Change to Mobile format
        $("#size").text('Change to mobile');
    }
});
// Manage tabletPortrait
tabletPortrait.addListener(function(m) {
    if (m.matches) {
        // Change to tabletPortrait format
        $("#size").text('Change to tablet portrait');
    }
});
// Manage tabletLandscape
tabletLandscape.addListener(function(m) {
    if (m.matches) {
        // Change to tabletLandscape format
        $("#size").text('Change to tablet landscape');
    } else {
        // Change to greater than 1199px
        $("#size").text('Change to greater than 1199px');
    }
})