DEV Community

Discussion on: Using media queries with JavaScript

Collapse
 
wparad profile image
Warren Parad • Edited

Often you are using a ux framework, and then would prefer to bind to the framework instead of hard coding the breakpoints. In that case, something like this is much better:

gist.github.com/wparad/6687a200ebb...

const xs = document.createElement('div');
xs.setAttribute('class', 'd-inline d-sm-none');

const sm = document.createElement('div');
sm.setAttribute('class', 'd-none d-sm-inline d-md-none');

const md = document.createElement('div');
md.setAttribute('class', 'd-none d-md-inline d-lg-none');

const lg = document.createElement('div');
lg.setAttribute('class', 'd-none d-lg-inline d-xl-none');

const xl = document.createElement('div');
xl.setAttribute('class', 'd-none d-xl-inline');

const breakpoints = { xs, sm, md, lg, xl };

import Vue from 'vue';
const activeBreakpoints = Vue.observable(Object.keys(breakpoints).reduce((a, b) => { a[b] = false; return a; }, {}));

function recalculate() {
  Object.keys(breakpoints).map(bp => {
    const style = window.getComputedStyle(breakpoints[bp]);
    Vue.set(activeBreakpoints, bp, !!style.display && style.display !== 'none');
  });
}

document.addEventListener('DOMContentLoaded', () => {
  try {
    const body = document.querySelector('body');
    const div = document.createElement('div');
    div.setAttribute('class', 'responsive-bootstrap-toolkit');
    Object.values(breakpoints).forEach(bp => { div.appendChild(bp); });
    body.appendChild(div);
    recalculate();
  } catch (error) { /* */ }
});

window.addEventListener('resize', recalculate);
export default activeBreakpoints;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
maroun_baydoun profile image
Maroun Baydoun

Thanks for sharing. There are indeed multiple solutions to this problem.