0

Is there an easy way to determine which breakpoint "mode" is currently in place using Javascript?

For example I am using SASS to set the view according to the $small-only, $medium-only etc. variables. However if the user has resized the browser and the $small-only breakpoint is being used I'd like to be able to query this in Javascript. So something like the following:

if ($small) {
    // do something
} else {
    // do something different
}
RRR
  • 3,509
  • 4
  • 29
  • 38
  • Are you looking for this solution? https://stackoverflow.com/questions/1248081/get-the-browser-viewport-dimensions-with-javascript – Adriano Nov 23 '17 at 11:37

1 Answers1

0

var debouncer = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; }
    if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

function breakpointCheck() {
  var $r = $(".responsiveChecker");
  
  if ($r.css("font-weight") === "500" ) {
    return 5;
  } else if ($r.css("font-weight") === "400" ) {
    return 4;
  } else if ($r.css("font-weight") === "300" ) {
    return 3;
  } else if ($r.css("font-weight") === "200" ) {
    return 2;
  } else if ($r.css("font-weight") === "100" ) {
    return 1;
  }
}

try { console.log("Breakpoint: " + breakpointCheck()); } catch(err) {}

$(window).on("resize", function() {
  debouncer(function() {
    console.log("Breakpoint: " + breakpointCheck());
  }, 500);
});
.responsiveChecker {
    font-weight: 500;
}
@media (max-width: 1600px) {
    .responsiveChecker {
        font-weight: 400;
    }
}
@media (max-width: 1120px) {
    .responsiveChecker {
        font-weight: 300
    }
}
@media (max-width: 767px) {
    .responsiveChecker {
        font-weight: 200
    }
}
@media (max-width: 374px) {
    .responsiveChecker {
        font-weight: 100
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="responsiveChecker"></div>

I have put together a codepen for what I think you are trying to achieve: https://codepen.io/MayhemBliz/pen/MOGMpW

MayhemBliz
  • 227
  • 2
  • 12