javascriptcssresponsive-designmatchmedia

Remove/add css classes on breakpoint with matchmedia.js


I have following code which works fine when the screen size is 770px and below (as determined by breakpoints):

    var handleMatchMedia = function (mediaQuery) {
      if (mediaQuery.matches) {

         $j(".view-all a").removeClass("button");
         $j(".view-all").removeClass("view-all");

    } else {

        $j(".view-all a").addClass("button");
        $j(".view-all").addClass("view-all");
    }
},

mql = window.matchMedia('all and (max-width: 770px)');

handleMatchMedia(mql); 
mql.addListener(handleMatchMedia); 

The problem is when the window is resized to 770px and up I lose my classes.

How to achive to change class on window resize?


Solution

  • Guessing what you're going for is changing the design page when media changes, by adding classes.

    Simply using css and media queries will achieve this:

    @media all and (max-width: 770px) {
      .viewall a {
        color: blue;
      }
    }
    

    but if you truly want it too be handled with javascript I'll recommend using another class as marker, like .adapt and changing the code to:

    var handleMatchMedia = function (mediaQuery) {
        if (mediaQuery.matches) {
           $j(".adapt a").removeClass("button");
           $j(".adapt").removeClass("view-all");
        } else {
           $j(".adapt a").addClass("button");
           $j(".adapt").addClass("view-all");
        }
    },
    
    mql = window.matchMedia('all and (max-width: 770px)');
    
    handleMatchMedia(mql); 
    mql.addListener(handleMatchMedia);