"Adjusting Flex Items Dynamically When Resizing the Screen

Hello everyone, I am a new web developer looking to create a calendar using only pure JS.

Currently, I have managed to wrap elements on overflow. My question is: how can I efficiently 'destroy' and 'create' new nodes in a responsive manner so that there is only 1 row with the optimal number of nodes? Here's a snippet where nodes are currently created manually:

for(var i = 0; i < 4; i++) addNewDayObject(i, "lel", "lel", 2015)

In my research, I stumbled upon media queries as a possible solution, but I would prefer not to hard code width values to trigger the code since the flex-items will have dynamic widths.

Answer №1

If you are looking to hide consecutive rows, one solution is to adjust the height of the container div to display only a single row at a time. This method works effectively if the height remains constant.

For a practical demonstration, check out my code on this fiddle.

CSS Styling:

#dayObjContainer {
    max-height: 124px; /* define maximum height */
    overflow: hidden;
    padding-bottom: 5px;
    display: flex;
    flex-grow: 1;
    flex-wrap: wrap;
}
.dayObj {
    padding: 10px 0px;
    width: 250px;
    color: #FFF5AA;
    background-color: #D4C96A;
    text-align: center;
    margin: 0px 5px 5px; /* additional bottom margin included */
    box-shadow: 2px 2px 5px #888888;
}

Answer №2

After stumbling upon the window.onresize function, I was able to solve my issue. I'm curious if there is comprehensive documentation in JavaScript or browsers that outlines all the available methods and properties. Trying to learn through guesswork and Google searches has been a bit slow for me so far.

window.onload = init;
var dayObjTemplate;
var containerRef;
var objCount = 0;
function init() {
  dayObjTemplate = document.getElementById("obj0");
  containerRef = dayObjTemplate.parentNode;
  dayObjTemplate.parentNode.removeChild(dayObjTemplate);

  for(var i = 0; i < 1; i++) addNewDayObject(11, 8, 2015)

  window.onresize = function updateNewContainerWidth(argument) {
    var conWdt = containerRef.offsetWidth;
    while(objCount < Math.floor(conWdt / (250+5))) {
      addNewDayObject(11, 8, 2015);
    }
    while(objCount > 1 && objCount > Math.floor(conWdt/(250+5))) {
      removeLastDayObject();
    }
  }
}

function removeLastDayObject() {
  containerRef.removeChild(document.getElementById("obj"+objCount));
  objCount--;
}

function addNewDayObject(day, month, year) {
  var d = new Date(year, month, day);
  var dayNames=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

  objCount++;
  var clone = dayObjTemplate.cloneNode(true);
  clone.id = "obj" + objCount;
  clone.getElementsByClassName("dayObjDayLabel")[0].innerHTML = dayNames[d.getDay() - 1];
  clone.getElementsByClassName("dayObjNumLabel")[0].innerHTML = day;
  clone.getElementsByClassName("dayObjMYLabel")[0].innerHTML = month + ", " + year

  document.getElementById("dayObjContainer").appendChild(clone);
}

Apologies for the messy code, but hopefully, this snippet can be helpful to others facing similar challenges like mine.

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

Angular 6 has numerous modules that have similar names but vary only in their letter casing

After running ng serve, I encountered an error that has me stumped. Everything was working fine with the new service I created until suddenly it all crashed :( I tried troubleshooting everything possible but to no avail. Even Google didn't provide any ...

How can data be transferred between web pages using jQuery or JavaScript?

Imagine having two different pages on a Classified car website: The first page is the search page, which displays a list of all cars. Check out a sample search page here The second page is the details page, where you can find specific information about a ...

"(PHP)WordPress produces a dynamic menu that adapts to different screen sizes

I recently created a menu on my WordPress site [ and I'm facing an issue with making it display vertically in a responsive way. The code in header.php is as follows: <!-- header --> <header> <div class="overNavPanel"> ...

Leveraging AngularJS, optimizing SEO, and hosting S3 static pages

My web application utilizes AngularJS for the front-end and .NET for the back-end. Within my application, there is a list view. When each item on the list is clicked, it retrieves a pre-rendered HTML page from an S3 bucket. I am implementing Angular stat ...

What may be causing a configuration problem with the USB binding in Electron?

I am encountering difficulties with installing USB modules in my electron app. Every time I attempt to install electron and its dependencies, I encounter the issues outlined below. Can someone please assist me in resolving this? If anyone has faced a simi ...

How can I showcase data retrieved from a function using Ajax Datatable?

I have implemented an Ajax function that retrieves data from a PHP file and displays it in a DataTable. Initially, this setup was working fine. However, when I added a new function to the PHP file, my Ajax function stopped retrieving data from the file. I ...

The background-color value specified for the get-function rgba-css-var is invalid and causing an error

I have completed the necessary steps to integrate Bootstrap 5 SASS into my ASPNET Core project. To begin, I right-clicked on the wwwroot directory and selected Add->Client-Side Library. From there, I chose the unpkg provider and added the <a href="/ ...

Error: Element type is invalid: a string was anticipated, but not found

I recently experimented with the example provided in React's documentation at this link and it functioned perfectly. My objective now is to create a button using material-ui. Can you identify what is causing the issue in this code? import * as R ...

Exploring the features of AngularJS, including ngTranscluded, angular.noop, and the differences between Inter

I have some doubts about certain concepts in AngularJS such as- Reference (The official documentation is a bit confusing on these topics.) When should we use the "ngTranscluded" directive? Under what circumstances would we need to create a function that ...

Testing the NestJS service with a real database comparison

I'm looking to test my Nest service using a real database, rather than just a mock object. While I understand that most unit tests should use mocks, there are times when testing against the actual database is more appropriate. After scouring through ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Steps to bring an image forward on a canvas to enable its onclick function

One of the challenges I'm facing involves an image of a pawn on a board. The image is set up with an onclick function that should trigger an alert when clicked. However, there is a canvas positioned above the image, which is interfering with the funct ...

Layering numerous backgrounds (Regular, Expanded, Regular) atop one another

After experiencing an issue with the background image not fitting the content properly at different resolutions, I attempted to divide the background into three parts and automatically stretch the middle section to fill the space between the top and bottom ...

Failed to update the innerHTML attribute for the anchor tag

I'm attempting to apply styles through DOM manipulation using Angular's renderer2. I have successfully updated styles for all HTML elements except for anchors. In the example below, I am trying to replace the text www.url.com with World within ...

I am currently utilizing diagrams in my three.js project to create various shapes of objects. Would you happen to know the best way to go about

I am utilizing the var shape = new THREE.Shape(); function. However, while using moveTo and lineTo, the diagram is not fully filled, and closePath() does not complete the path after using lineTo. Any insights into this issue would be appreciated. Here is ...

What are some strategies for handling data after it has been retrieved using Axios?

In my current project, I am working with MySQL database and fetching data using Axios and a useEffect hook. Once the data is retrieved, I pass it to a component as a prop. Here's how: const Component = () => { //Database URL const urlProxy = &q ...

Navigating race conditions within Node.js++]= can be challenging, but there are strategies

In the process of developing a MERN full stack application, I encountered a scenario where the frontend initiates an api call to "/createDeckOfCards" on my NodeJS backend. The main objective is to generate a new deck of cards upon clicking a button and the ...

Step-by-step guide to enabling native Bootstrap 2.3.2 JavaScript elements within Liferay

In my web development project, I am working with Liferay 6.2 and utilizing Alloy UI's version of Bootstrap in the html pages by adding these lines: <link href="http://cdn.alloyui.com/2.5.0/aui-css/css/bootstrap.min.css" rel="stylesheet" /> < ...

When adjusting the month/year, the Material Date Picker extends beyond its container

Currently, I have an Angular 18 application with a page that includes a material date picker component. When I open the Date Picker, everything displays correctly. However, when I try to change the month using the left/right arrow or the year, the data co ...

Listening for a custom event with jQuery

Here is the code snippet that I am working with: myCustomMethod(function(){ $(document).on('click','#element',function(){ console.log('First call'); }); }); setTimeout(function(){ myCustomMethod(function( ...