Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 203
user642523 Avatar asked Oct 20 '22 13:10

user642523


1 Answers

You need to cache your selectors. See jsfiddle as well :

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

handleMatchMedia(mql); 
mql.addListener(handleMatchMedia); 
like image 153
vittore Avatar answered Oct 27 '22 23:10

vittore