Utilize the splice function when resizing the window based on specific breakpoints

On a series of div elements, I have implemented some JS/jQuery code that organizes them by wrapping every three elements in a container with the class .each-row.

<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>

results in:

<div class="each-row">
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
</div>
<div class="each-row">
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
</div>

The JavaScript code used for this functionality is as follows:

// Grab all the .bricks
var brick = $('.container .brick');
// Iterate through all the .bricks
for (var i = 0; i < brick.length; i += 3) {
    // Create container
    var brickContainer = $('<div />', {
        class: 'each-row'
    });
    // Wrap all the .bricks inside the container
    brick.slice(i, i + 3).wrapAll(brickContainer);
}

This solution works effectively, however, I aim to incorporate breakpoints so that under different screen sizes, the elements are organized differently. When the screen size is 767px or below, each .brick should be wrapped in an each-row, and if it's less than 1224px, wrap every two bricks, otherwise wrap every three.

I have already achieved this through the use of the resize function and even provided a demonstration on JSFiddle. The only issue encountered is that due to resizing, the each-row gets added at every pixel change. When inspecting the DOM during the resize process on JSfiddle, you'll notice the continuous addition of each-row.

Any suggestions on how to resolve this would be greatly appreciated.

Thank you, R

Answer №1

Make sure to first unwrap the elements before wrapping them again.

function adjustGrid() {

    $('.each-row').each(function(index, eachRow){
        $(eachRow) // choose the row
            .children()  // select its children
            .detach()  // disconnect them from the row
            .appendTo($(eachRow).parent()); // add them to the row's parent
        $(eachRow).remove(); // delete the empty row
    });
    // remainder of your code here
});

I have made updates to your example on fiddle: http://jsfiddle.net/b2YKZ/4/

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

Troubleshooting a Navigation Styling Issue in HTML and CSS

I'm struggling to position my drop-down menus correctly in my WordPress theme navigation. They are appearing far away from the nav bar and end up near the top left corner of the screen when I hover over a ul li >. Here is the CSS code I am using: ...

An error occurred during runtime due to a TypeError when trying to execute the 'setItem' function on 'Storage'. The error message indicates that 2 arguments are required for this function, but only 1 argument

Having an issue with the local storage not working and the screen showing up as white in the browser. 5 | const getFromLocalStorage = () => { 6 | if (typeof window !== undefined) { > 7 | const value = localStorage.getItem(& ...

Ajax fails to send requests to PHP after changing the URL directory

After struggling to find a solution to my query, I have come to the realization that it has not been asked before. Despite enabling rewrite rules on my apache2 server in the .htaccess file located in the root directory, I am facing an issue with my ajax sc ...

Modify the role attribute on elements in real-time to enhance accessibility

On a German website, we have implemented a textfield with autocomplete functionality in a form. As the user types into the input field, a dropdown menu of suggestions appears for them to select from. It is crucial that this feature is fully accessible with ...

How can I efficiently transfer a JavaScript array to a PHP script using the GET method?

My web application is designed with jQuery allowing users to manipulate visual elements. The next step is sending the JavaScript object state to PHP for storage in a database. While I prefer using GET, I am open to solutions that involve POST submission as ...

The Ajax URL is failing to connect with the controller through IIS

I am facing an issue where the application gets stuck in the Home controller when running it on IIS. It doesn't progress to the next controller (Data controller) as specified in the URL. However, when I run it in debug mode, everything works fine. How ...

Trigger the activation of an input field upon clicking an image labeled "edit"

I am currently developing a website where administrators have access to a dashboard page that displays a list of users. I am looking to implement a feature that allows admins to change the roles of other users directly from the same table row. Below is th ...

Dynamically and asynchronously loading numerous LinkedIn share buttons on a page

On my page, I have a grid of post thumbnails that are fetched via AJAX and can be filtered. When a user clicks on a thumbnail, a carousel opens with the selected post centered. In this carousel, each post has a LinkedIn share button integrated. The issue ...

Angular 2: The window.crypto.subtle.importKey function functions properly on 'localhost' but encounters issues on an 'ip' address

As a newcomer to Angular 2, I am working on creating a login form that encrypts and sends the user's emailid and password to the server. I have successfully implemented AES-ECB using AES-CTR from the following link: https://github.com/diafygi/webcry ...

jQuery functions like fadeOut and fadeIn are working perfectly fine, but for some reason, shuffle seems to be

I have a list that needs to undergo a shuffle animation when a button is clicked. The process I need is: Items in the list should fade out The items should then be randomized Finally, the items should fade back in. Each individual part of my script work ...

Having trouble with jQuery div height expansion not functioning properly?

Having a bit of trouble with my jQuery. Trying to make a div element expand in height but can't seem to get it right. Here's the script I'm using: <script> $('.button').click(function(){ $('#footer_container').anim ...

The speed of the Ionic app is disappointingly sluggish on devices, causing significant delays

After testing my app in Ionic Lab, it runs smoothly. However, when I create the apk file and install it on my device, the performance is very slow. There are delays in clicking on buttons, pushing pages, opening modals, and closing modals. It seems like t ...

When utilizing document.addEventListener in JavaScript, Firefox fails to report exceptions triggered by DOMContentLoaded

I'm developing an internal framework that must be independent of any external dependencies such as jQuery. I'm working on implementing a custom DOM ready-style functionality, where callbacks in the ready queue should continue executing even if an ...

Does anyone have tips on how to upload images to MongoDB using React?

Currently, I am working on a project that requires an image upload feature for users. These images need to be stored in MongoDB so that they can be viewed by the user later on. Can anyone offer assistance with this? I have successfully configured my datab ...

Utilizing JQuery for Next and Previous Navigation Buttons

Currently, I am in the process of developing a website where users can click on project images to view detailed information and additional images in a full-screen overlay. I am also implementing next and previous buttons to navigate through the projects. A ...

The class within the div element will fail to pick up the specified CSS styles

I've been troubleshooting an issue with a newly created div that's not picking up its corresponding styles from the stylesheet. It's frustrating and I could really use some help. Here is the HTML: <div class="2columnlayout"> < ...

Searching for partial nodes

I came across a helpful tutorial that explains how to perform a partial search. My goal is to have it so that when someone enters the text geor, it can locate a user named george. db.stores.find({storeName : {$regex : /Geor/}}).pretty() However, I am str ...

Best practice in TypeScript for handling an Enum with a switch-case to assign a variable

Here's an issue I'm facing: I have a variable called Difficulty that is an Enum. Within a function, I need to set the configuration DifficultyConfig based on the value of Difficulty. The current solution I have in mind seems overly complicated: ...

Utilizing a drop-down menu to display two distinct sets of data tables

After spending some time on my WordPress site, I've encountered a problem that has me feeling stuck. Currently, I have two functioning datatables which are displaying one on top of the other on the page. Additionally, there is a dropdown selection box ...

Use jQuery to set a Firebase image as the background of a div element

Is there a way to fetch an image from Firebase and use it as the background for a div element? I've tried several approaches without success. Could someone share some examples on how to achieve this? <div class="museBGSize rounded-corners grpelem" ...