My Technical Notes

Sunday, 8 January 2017

Finding `max-width` and `max-device-width` programmatically

The following Javascript code finds out the `max-width` and `max-device-width` of a page/device:


(function () {
    function getWidth(type) {
        var startWidth = 100;
        var endWidth = 1000;

        for (var i = startWidth; i <= endWidth; ++i) {
            if (!(window.matchMedia("(min-" + type + ": " + i + "px)").matches)) {
                return i - 1;
            }
        }

        return ">= 1000";
    }

    alert('max-width is ' + getWidth('width') + 'px and max-device-width is ' + getWidth('device-width') + 'px');
})();

No comments: