Writing JavaScript that responds to media queries

I wanted to change the layout of my blog on mobile screens such that the content from the "Elsewhere" right hand column combined with the main column in the correct order (issue #165). I couldn't find a way to do this in pure CSS without duplicating a bunch of content, so I decided to do it with JavaScript.

I needed to apply some changes to the DOM if the users window was smaller than 800px - or if the user resized their window to less than 800px after they had first loaded the page.

Here's the JavaScript I came up with, using Window.matchMedia():

window.hasBeenRearrangedForMobile = false;
function rearrangeForMobile() {
  // Make changes to the DOM here
}
function conditionalRearrange(m) {
  if (m.matches && !window.hasBeenRearrangedForMobile) {
    rearrangeForMobile();
    window.hasBeenRearrangedForMobile = true;
  }
}
var mediaMatcher = window.matchMedia('(max-width: 800px)');
conditionalRearrange(mediaMatcher);
mediaMatcher.addListener(conditionalRearrange);

Full code is here.

That rearrangeForMobile() function makes changes to the DOM, by copying some content from the sidebar into the main column. Media queries in my CSS then control the display of that content at different screen sizes - so if the user changes the width of the page things will continue to display correctly based on the current width, without needing to execute extra JavaScript.

Here's the accompanying CSS:

.elsewhere-date {
    display: none;
}

#primary .elsewhere-in-primary {
    display: none;
}

@media (max-width: 800px) {
  #primary .elsewhere-in-primary {
    display: block;
  }
  .elsewhere-date {
    display: inline;
  }
  .hide-secondary-on-mobile {
    display: none;
  }
  // ...
}

Created 2020-10-21T20:06:08-07:00, updated 2020-10-22T08:04:15-07:00 · History · Edit