I am currently working on a script to reverse the order of two divs when the client's window is resized; however, I seem to be stuck in a loop. Although flexbox could easily solve this issue, I am determined to figure it out using JavaScript as part of my learning process with the language.
My goal is to rearrange the divs, like changing flex-direction: column-reverse;
, when the window size drops below 58em. If the window remains unchanged or exceeds 58em, the function should not activate.
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>