I'm very new to JavaScript so I thought I'd ask for someone to have a quick look over this to make sure it isn't brittle, buggy, or completely unnecessary. It may be all three. I also thought it might help someone in the future (if correct), as I found lots of different suggestions I don't think I needed including looping through all the child nodes and using enquire.js.

It moves a div from one parent container to another depending on whether a media query is relevant. The target div also moves with a normal css media query.

codepen (make the container height a fair bit taller than the width)

<div class="wrapper">
  <div class="container container1" id="c1">
    <div class="item item1">1</div>
    <div class="item item2" id="toMove">2</div>
    <div class="item item3" id="item3">3</div>

  <div class="container container2" id="c2">
    <div class="item item4">4</div>
    <!-- Item3 will end up here -->


  flex-direction: column;
  width: 100%;
  background: #eaeaea;

@media (min-aspect-ratio: 4/5){
    flex-direction: row;

  display: flex;
  justify-content: space-around;

  flex-basis: 66.6%;
  background: red;

  flex-basis: 33.3%;
  background: blue;

  background: white;
  padding: 50px;
  margin: 20px;
  border: 1px solid #333;


var container1 = document.getElementById('c1');
var container2 = document.getElementById('c2');
var item = document.getElementById('toMove');

matchMedia("screen and (min-aspect-ratio:4/5)").addListener(function(mql) {
   if(mql.matches) {
       moveElement(item, container1);
   else {
       moveElement(item, container2);

function moveElement(source, target){

Appreciate the feedback as I don't really know what I'm doing with JS!

*fixed the problem in the example RE moving the item back to its original location. I just call the method container1.insertBefore(toMove, item3); in the 'else' block, instead of calling moveElement(). (where item3 is a variable pointing to #item3)

In case that helps anyone.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.