JQuery Match Media Function

Using the match media jquery function, change the object behaviour according device resolutions. Match media jquery find the trageted resolution and replace the CSS or object with the new property.

Example: In this tutorial we can learn how to change the desktop view image to mobile view.

JQuery Match Media Function
<img src="images/desktop-view-image.jpg">

# Replace the image (desktop-view-image.jpg) with the new image (mobile-view-image.jpg) in mobile view or different resolutions.

Below are the javascript code for find the device resolution. if the targeting resolutions are match the below script replace the image with another image.

$(function() {
    if (window.matchMedia("(max-width: 767px)").matches) {
        $('#demo').attr('src', 'images/fullimage1-m.jpg');
     } else {
        $('#demo').attr('src', 'images/fullimage1.jpg');

Need to assaign one id to <img> tag for replace the image

<img id="demo" src="images/desktop-view-image.jpg">

Below are the example of owl carousel slider, using the match media function replacing the big image to small image accoriding to mobile view for better image readability.

  • Html
  • Javascript
<div id='owl-demo' class='owl-carousel owl-theme'>
    <div class='item'>
        <img src='images/banner.jpg' alt=''>

# Replace the image (banner.jpg) with the (banner-m.jpg) in differnt resolution
  $(function() {
      var ravenous = function() {
          if (window.matchMedia('(max-width: 767px)').matches)
              var boat="m";
              $('#owl-demo .item img').attr('src', function(index, attr) {
                  return attr.replace(/\.[^.]*$/, '-'+ boat +'$&');
          else {

In this tutorial we learn the how to get device resolution using match media function and apply or replace the new properties to exiting class or tag.

Window matchMedia() Method