Для отслеживания текущего размера экрана устройства и добавления соответствующих CSS-классов на элемент <body>
Определяет набор устройств (rangeDevices) с пороговыми значениями ширины экрана (мобильные, планшеты, ноутбуки и т.д.)
Примеры классов: js-device-mobile, js-device-tablet и т.д.
js-device-mobile, js-device-tablet, js-device-desktop new CustomDevices();
new CustomDevices({
"mobile": {
name: 'mobile',
value: 767,
},
"tablet": {
name: 'tablet',
value: 1023,
},
"laptop": {
name: 'laptop',
value: 1279,
},
"desktop": {
name: 'desktop',
value: 1920,
}
});
/**
*
* Custom Devices
* Для отслеживания текущего размера экрана устройства и добавления соответствующих CSS-классов на элемент <body>
*
* @author Mihail Pridannikov
* @copyright 2023-2026, Mihail Pridannikov
* @license MIT
* @version 2.0.0
* @release 2024
* @link https://github.com/mihail-174/custom_devices
*
*/
window.rangeDevices = {
"mobile-s": {
name: 'mobile-s',
value: 479,
},
"mobile": {
name: 'mobile',
value: 767,
},
"tablet": {
name: 'tablet',
value: 1023,
},
"laptop": {
name: 'laptop',
value: 1279,
},
"desktop": {
name: 'desktop',
value: 1920,
}
};
const CustomDevices = function(settings) {
rangeDevices = (typeof settings === 'undefined') ? rangeDevices : settings;
let data = rangeDevices;
this.init = function () {
Object.values(data).map((item, index) => {
let prev = this.getPrevBreakpoint(index),
current = this.getCurrentBreakpoint(index, item);
// console.log(`${prev+1} — ${current}`)
if (document.body.offsetWidth > prev && (current > 0 ? document.body.offsetWidth <= current : prev)) {
this.addingClass(item);
}
});
window.addEventListener('resize', e => {
this.handlerResizeWindow();
}, true);
}
this.handlerResizeWindow = function () {
this.removingClass();
Object.values(data).map((item, index) => {
let prev = this.getPrevBreakpoint(index),
current = this.getCurrentBreakpoint(index, item);
// console.log(`${prev+1} — ${current}`)
if (document.body.offsetWidth > prev && (current > 0 ? document.body.offsetWidth <= current : prev)) {
this.addingClass(item);
}
});
}
this.addingClass = function (item) {
document.body.classList.add(`js-device-${item.name}`);
}
this.removingClass = function () {
document.body.classList.remove(...[...document.body.classList].filter(n => n.startsWith('js-device-')));
}
this.getPrevBreakpoint = function (index) {
return index === 0 ? 0 : data[Object.keys(data)[index-1]].value;
}
this.getCurrentBreakpoint = function (index, item) {
return (index === Object.keys(data).length-1) ? 0 : item.value;
}
this.init();
}