Activate resizing only a single time

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>

Answer №1

It is recommended to use the match media event instead of relying on the resize event for better performance.

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


/* Any other code that reverses the order of elements can be implemented 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

insert the "tr" element directly following the button

I am looking for a way to allow the user to add another input file right next to the button, so they can select and send multiple files at once. https://i.sstatic.net/TI4eJ.png I have tried using various solutions I found during my search but none of the ...

Highcharts memory leakage issue arises when working with jQuery version 2.X

After extensive testing on my AngularJS application, I have discovered a memory leak when using Highcharts with the latest version of jQuery (2.1.4). Below are links to two plunkers for comparison: Using jQuery 1.8.2: http://plnkr.co/edit/lQ6n5Eo2wHqt35OV ...

What are the tips for aligning this button perfectly on the page, despite being centered in a computer's resolution?

Dealing with Responsive Design Hey there! I'm having an issue with my Bootstrap layout. I managed to center a button, but when I adjust the resolution or make it smaller, the button wraps and shifts to the right. Can anyone help me figure out what we ...

What could be the reason behind the disappearance of text from the previously highlighted button in my calculator's "button grid" when I change the highlighted button?

Currently, I am in the midst of creating a tip calculator with a grid consisting of various percentage buttons. My main objective is to change the font and background color when any tip button is selected. Nevertheless, an issue has surfaced - whenever I h ...

JavaScript Recursive Function for Generating FancyTree JSON Structure

I'm currently building an array of JSON objects for FancyTree (https://github.com/mar10/fancytree/wiki/TutorialLoadData). My JSON source is from the Jira REST service, and its structure can vary widely. Therefore, the code to construct the array of JS ...

Using CSS in Rails based on a certain condition

My project involves creating an app with a specific view. Within this view, I must check a condition and if it is met, I need to color a table row accordingly. While the simplest solution would be to modify the header within the view, I prefer to keep al ...

Issue with Angular 17 button click functionality not functioning as expected

Having trouble with a button that should trigger the function fun(). Here's the code snippet I'm using. In my TS file: fun(): void { this.test = 'You are my hero!'; alert('hello') } Here is the respective HTML: &l ...

An issue occurred while running the "gulp test" command due to a problem with the 'gulp-tslint-log'

Having issues running gulp on a JHipster generated project. I've already installed all node_modules using npm install and here are my package.json and gulpfile.js: { "name": "myapp", "version": "0.0.0", "description": "Description for myapp", ...

Updating REST API: Sending a PUT request without requiring all data to be included in json format

I have a controller set up for updating user data. The controller can accept up to 4 values. I am wondering if it is possible to only update the name field when sending data to this route, leaving the rest of the fields unchanged (and not empty). Should ...

dynamic webpage resizing using html and css

Looking for a way to make my SharePoint window automatically resize when the user changes their browser size. I'm using the web version of SharePoint at work and don't have access to Designer. <style type="text/css"> #dgwrap { HEIGHT: ...

Checkbox does not trigger onCheck event

I am facing an issue with a checkbox component from material-ui where the onCheck event is not firing. <Checkbox label="label" onCheck={onCheck} checked={currentDocument.ispublic} /> function onCheck() { currentDocument.ispublic = !current ...

Creating dynamic buttons and textboxes on a JSP page

<form:form action="approveAccount.html" method="GET"> <input type="submit" value="approvAll"/> <p>List of Pending Accounts for Approval</p> <c:forEach items="${accountIdList}" var="val"> <li>${val}</li> ...

Carousel Alert: Ensure that every child within the list is assigned a distinct "key" property

I'm experiencing an issue that is proving to be more challenging than usual, as it appears to be related to a specific library. I understand that using a key from a file is not ideal, but the plan is for it to come from a database in the future. Libr ...

Steps for launching an application through a hyperlink to appear on the foreground rather than the background

For my project, I am utilizing "a href" to open a windows application. <a href={`enter app here`}> //Similar concept as mailto The issue I am facing is that it opens the application in the background rather than bringing it to the foreground. Esse ...

Passing a JavaScript variable to PHP within an HTML document: Parsing data from Wikipedia

I am currently working on passing a JavaScript variable named $url to a PHP function in the same HTML file. The idea is that a user inputs a species into a textbox, and the Wikipedia API is called to check if the input matches a Wikipedia page. If a match ...

Validating Form Inputs using JQuery and Bootstrap 4 to Enhance User Experience

I came across a helpful post about using Bootstrap with jQuery Validation Plugin, but it's specifically for Bootstrap 3, not Bootstrap 4. I've been trying to integrate JQuery Validate with Bootstrap 4, but I'm struggling to make the label a ...

Tips for moving a title sideways and adjusting the bottom section by x pixels

I am seeking to accomplish a design similar to this using CSS in order to create a title of <h1>DISCOVER <span>WEB 3</span> DIMENSIONS</h1>. How do you recommend achieving this? Thank you, I have searched on Google and asked frie ...

Getting a random value within a Struts set tag can be achieved by utilizing the <

Using struts2 tags in my application, I am trying to dynamically change the value in a JavaScript array using s:set tags. However, when I add the values dynamically, the output I get is 2012 - diff + 1, whereas I am expecting 2011. How can I achieve this? ...

Error occurred in AngularJS when trying to pass a parameter from an HTML page in order to retrieve data using

I am encountering an issue when attempting to pass a parameter from the HTML page to delete a row from the database. The http.get() method retrieves data for all books, and I am passing the ID for a specific book for deletion. However, I am facing a syntax ...

bind a class property dynamically in real-time

I need to dynamically generate a TypeScript class and then add a property to it on the go. The property could be of any type like a function, Promise, etc., and should use this with the intention that it refers to the class itself. let MyClass = class{ ...