Technique for wrapping and unwrapping a div during resizing?

I've been experimenting with using if else statements to achieve a simple task, but I'm struggling to reverse the wrapping of boxes after resizing the window above 650px.

The goal is to have the boxes wrapped in a div when the window width is below 650px and then unwrapped once the window is resized above 650px.

Any suggestions on how I can accomplish this?

$(window).resize(function() {
  if ($(window).width() < 650)
    $('.box').wrap("<div class='boxwrap'><div/>")
});

$(window).resize(function() {
  if ($(window).width() > 650)
    $('.box').unwrap("<div class='boxwrap'><div/>")
});
  #cat-area {
  width: 100%;
  display: inline-block;
  text-align: center;
  background-color: red;
}

#cat-container {
  background-color: yellow;
  width: 92.5%;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
}

.box {
  display: inline-block;
  width: 20%;
  height: 20%;
  max-height: 300px;
  max-width: 300px;
  min-height: 100px;
  min-width: 100px;
  padding: 1%;
  background-color: #d7d7d7;
}

@media only screen and (max-width: 650px) {
  #cat-area {
    width: 100%;
    display: block;
    text-align: center;
    background-color: red;
  }
  #cat-container {
    background-color: blue;
    width: 92.5%;
    display: block;
  }
  .box {
    position: relative;
    display: block;
    margin: 4px 0px;
  }
  .boxwrap {
    background-color: #d7d7d7;
    width: 100%;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="cat-area">
  <div id="cat-container">
    <img class="box" src="http://via.placeholder.com/200x200">
    <img class="box" src="http://via.placeholder.com/200x200">
    <img class="box" src="http://via.placeholder.com/200x200">
    <img class="box" src="http://via.placeholder.com/200x200">

  </div>
</div>

Answer №1

I encountered a similar issue recently and managed to find a solution. Here is a quick guide on how you can tackle this problem:

  1. Take note of the initial page width
  2. Upon resizing, wait for a short moment (after resizing stops) and record the new width
  3. Compare the two values to decide whether action is needed or not
  4. Update the comparison width to the new value for the next resize event

To see this in action, run the code snippet below, expand it to full screen, and adjust the browser size to observe the effect.

$(function() {
  var resizeTimer;
  var initialSize = $(window).width();
  $(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
      var delayedSize = $(window).width();
      // Do nothing if we resize within the 650 threshold
      if ((initialSize > 650 && delayedSize > 650) || (initialSize < 650 && delayedSize < 650)) {
        return
      }
      // If we cross the 650 threshold, take action
      else {
        if (delayedSize > 650) {
          $('#cat-container').unwrap('#cat-area');
        } else if (delayedSize <= 650) {
          $('#cat-container').wrap('<div id="cat-area"></div>');
        }
      }

      initialSize = delayedSize;
    }, 250);
  });
});
#cat-area {
  background-color: gold;
  padding: 10px;
}
#cat-container {
  background-color: slategray;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cat-area">
  <div id="cat-container">
    <img class="box" src="http://via.placeholder.com/200x200">
    <img class="box" src="http://via.placeholder.com/200x200">
    <img class="box" src="http://via.placeholder.com/200x200">
    <img class="box" src="http://via.placeholder.com/200x200">
  </div>
</div>

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

Looping through an array in PHP

Is there a way to loop through an array in my code? Here is the initial version of my script: $val=array( array("value" => "Male","label" => "Male"), array("value" => "Female","label" => "Femal"), ); my_form("Gender","select","gender",$va ...

Avoid enlarging images on your desktop beyond their original size

I currently have a random image script located in the folder /1 on my public_html. The script is being displayed on my index.html page using the following code: <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scal ...

What are the steps for sending data to Web Api MVC 4?

I am having difficulty submitting data from a view page to a separate Web Api MVC 4 project. Both my Application and Web Api are housed in different projects. Below is the jQuery Ajax call I am using: $.ajax({ url: 'http://localhost/api/C ...

Executing function inside an Angular factory

I am currently working with an Angular factory that contains various functions. My goal is to use myService to retrieve data, and upon successful retrieval, call another function within the factory: myApp.factory('myFactory', function($http) { ...

Tips for incorporating additional items into an established useState array utilizing map() or foreach()?

I'm working on developing a social media platform similar to Twitter, and I'm facing challenges with the news feed functionality. Essentially, the news feed is supposed to fetch tweets from my firebase database for each user followed by the curre ...

Navigating the world of Python HTML Scraping and managing XHR requests

I am struggling to extract the complete HTML content from a journal URL. I have tried various methods mentioned on this platform, but none of them are giving me the desired result with the .text or .json() functions of requests.get. My objective is to re ...

How can we transition a line of code from PHP to Smarty?

I'm currently working on converting a php line of code to Smarty. I've managed to convert the variable successfully, but I am struggling with incorporating the small syntax before it. Below are both sets of syntax - how can I include link_it with ...

Using jQuery for validation and accepting only files of type "image/*"

I'm currently working on a form that includes various text fields and an input element like the one below: <input class='ignore' name='photo' id='photo' type='file' accept="image/*"/> Furthermore, I have ...

Exporting mongoose query results with a data object is not possible

I'm struggling with my mongoose query. I want to update the "entry_count" property of an Entry object with the result of a count query, but for some reason I am unable to export the data after making the update. Although I can retrieve the data succe ...

Attempting to grasp the concept of implementing an If statement in conjunction with an event

Check out this HTML code snippet <body> <div> <button> Button A </button> <button> Button B </button> <button> Button C </button> </div> </body> This is my att ...

Select all checkboxes except the ones that are disabled using jQuery

Looking for a solution to select only enabled checkboxes using jQuery. Here is the JSP code I have: <th><input name="checkAll" type="checkbox" onClick="toggleCheck(this, this.form.poFulfill);"/></th> Each row determines if the checkbox ...

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

Issue with playing audio file using HowlerJS

Having trouble playing a .mp3 file in my project directory with Howler. I'm not sure if there's an error in my src. When I tried playing an online hosted audio file, it worked fine. I've placed the audio file in the same directory as Slideon ...

Dynamically switch between showing more and showing less content on each div

Whenever the specific show more button is clicked, the content should be displayed without causing the entire component to re-render. I have tried using a useState, but each time the button is clicked, the whole component re-renders, resulting in long load ...

JavaScript Character Set on the Dynamic Page in Delphi

Within my Delphi application, I am dynamically generating HTML content. Displaying UTF-8 encoded strings in the webpage body is not an issue for me as I use HTMLEscape to encode regular strings (ensuring all strings in the list are properly escaped). The ...

Drop-down menu vanishes when hovered over (Mozilla Firefox)

I am facing an issue where a button with a dropdown menu that appears on hover works perfectly fine in Chrome, but in Firefox the dropdown disappears when I try to select an item from it. Here is my CSS and JS fiddle for reference. button { position:re ...

My component in React is not getting rerendered despite changes in the state

Here's a straightforward scenario: index.tsx functions as the provider, while app.tsx serves as the consumer. Despite clicking the 'next' button and incrementing the questionNumber in the contexts, the QuestionDeserializer component fails to ...

What is the best way to sort through items in ngRepeat based on an array of numbers?

I'm having trouble figuring out how to filter a list of results in an ng-repeat based on an array of numbers. These numbers can determine which results I want to display or hide. Currently, I am able to use a filter in the view to filter by one number ...

Distinguishing Features of HTML, Canvas, and WebGL

Is there a way to draw images in WebGL with the same quality as HTML, even when downscaled? I've noticed that scaling down images in WebGL results in poor quality compared to HTML. After reading about 'Handling High DPI (Retina) displays in WebGL ...

Locating the matching value in the <select> element and showcasing it

I'm trying to create a function where selecting an option from one dropdown menu will display the corresponding value in another column. For instance, if someone chooses "3" from the first dropdown, the value displayed in the third column should be "3 ...