smugdessert
smugdessert

Reputation: 5

Trigger resize only once

I am trying to reverse two divs when the client's window is resized, but my function loops. I know that this can be made very easy using flexbox, but I am more interested in understanding how to make it work using JS. Just got into learning JS and I am experimenting with functions.

when the client's window is below 58em, I want the divs to rearrange - like flex-direction: column-reverse; for example. when the window is not resized or it's size is bigger than 58em, the function should not do anything

var reverse = document.querySelectorAll(".reverse");

function reverseChildren(parent) {
  for (var i = 1; i < parent.childNodes.length; i++){
    parent.insertBefore(parent.childNodes[i], parent.firstChild);
  }
}

window.addEventListener('resize', function () {
if (window.matchMedia("(max-width: 58em)").matches) {
    for (i = 0; i < reverse.length; i++) {
      reverseChildren(reverse[i]);
    }
  }
});
<div class=" reverse">
  <div class="first">
    <h4>some text</h4>
  </div>

  <div class="second">
    <img src='https://images.unsplash.com/photo-1430026996702-608b84ce9281?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=600&h=338&fit=crop&s=363a88755a7b87635641969a8d66f7aa' alt="Registration screen">
  </div>
</div>

Upvotes: 0

Views: 176

Answers (1)

user7148391
user7148391

Reputation:

You should listen for the match media instead of the resize event.

var reverse = document.querySelectorAll(".reverse");


/* Any other code that reverses the ordre of elements is viable within this function */
function reverseChildren(parent) {
  let children = [];
  for (var i = 0; i < parent.children.length; i++) {
    children.push(parent.children[i]);
  }
  children = children.reverse().map(item => item.outerHTML).join('');
  parent.innerHTML = children;
}



let media = window.matchMedia("(max-width: 58em)");
media.addListener(() => {
  for (var i = 0; i < reverse.length; i++) {
    reverseChildren(reverse[i]);
  }
});
<div class=" reverse">
  <div class="first">
    <h4>some text</h4>
  </div>

  <div class="second">
    <img src='https://images.unsplash.com/photo-1430026996702-608b84ce9281?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=600&h=338&fit=crop&s=363a88755a7b87635641969a8d66f7aa' alt="Registration screen">
  </div>
</div>
<span class="mq-value"></span>

Upvotes: 1

Related Questions