Using jQuery to generate columns depending on the quantity of occurrences of an element inside a specific Div

I've encountered a challenge while using a plugin that restricts access to the HTML, but allows for adding CSS and Javascript. I am aiming to achieve the following:

  1. Determine if a specific class within a div is active
  2. If it's 'active', locate all instances of labels inside that element
  3. Arrange groups of 8 label instances into columns (33% width of parent container)
  4. If there are less than 8 instances, take no action

Despite several attempts, I'm struggling to find the right approach. Here is an excerpt of my current code:

function columnSnap() {
  $('.productFilter').each(function() {

    if ($(this).is(":visible")) {
      $(this).find('label').addClass('randomClass');
      if ($('.randomClass').length >= 8) {
        //Get next 8 instances and group within a created div
        //Continue until number of instances of randomClass finishes
      }
    }
  });
}
columnSnap();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productFilter">
  <div class="randomDiv">
  </div>
  <div class="checklist">
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
    <label class="randomClass"></label>
  </div>
</div>

I have a general idea of what needs to be done but facing difficulties with implementation. Any advice or suggestions would be greatly appreciated. Thank you

Answer №1

Let me provide the solution for this issue, and I'd like to highlight a fundamental flaw in your code. The line that reads

if ($('.randomClass').length >= 8) {
is not correct. It's incorrect because it counts the total number of labels overall. This isn't accurate because I assume you want to group 8 labels within each productFilter

Imagine there are 2 productFilter divs, one with 5 labels and the other with 4 labels. According to your intention, they shouldn't be grouped together since the number of labels within each productFIlter div is less than 8. However, they will erroneously be grouped together because the mentioned code will count the total labels as 9 (5+4), which is > 8

Therefore, that section should be modified to:

if ($(this).find('.randomClass').length >= 8)

Now that's clear, here's the code snippet below. You can find the corresponding JSFIDDLE link as well

function columnSnap() {
jQuery('.productFilter').each(function(){
i = 0;
if(jQuery(this).is(":visible")) {
jQuery(this).find('label').addClass('randomClass');
lenChild = jQuery(this).find('.randomClass').length;
if (lenChild >= 8) {
var parentContainer = jQuery(this);

v2 = (Math.floor(lenChild/8) * 8);
parentElem = 0;
jQuery(this).find('.randomClass').each(function(){
if(i < v2) {
if(i%8 == 0) {
if(i != 0) 
jQuery(parentElem).appendTo(jQuery(parentContainer));
//parentElem = jQuery('#instancecontainer .instanceHolder').clone();
parentElem = jQuery('<div class="instanceHolder"></div>');
}
jQuery(this).appendTo(jQuery(parentElem));
i++;
}
});
jQuery(parentElem).appendTo(jQuery(parentContainer));
}
}
});

jQuery('#move').click(function(){
columnSnap();
});
   
.productFilter {
  border:2px solid #ccc;
  margin:20px 0;
}
.randomClass {
  display:inline-block;
  padding:10px;
  min-width:10px;
  margin:5px;
  background:red;
}
.instanceHolder {
  border:2px solid green;
  margin:10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productFilter">
    <div class="randomDiv">
    </div>
    <div class="checklist">
        <label class="randomClass">1</label>
        <label class="randomClass">2</label>
        <label class="randomClass">3</label>
        <label class="randomClass">4</label>
        <label class="randomClass">5</label>
        <label class="randomClass">6</label>
        <label class="randomClass">7</label>
        <label class="randomClass">8</label>
        <label class="randomClass">9</label>
        <label class="randomClass">10</label>
        <label class="randomClass">11</label>
        <label class="randomClass">12</label>
        <label class="randomClass">13</label>
        <label class="randomClass">14</label>
        <label class="randomClass">15</label>
        <label class="randomClass">16</label>
        <label class="randomClass">17</label>
        <label class="randomClass">18</label>
    </div>
</div>
<div class="productFilter">
    <div class="randomDiv">
    </div>
    <div class="checklist">
        <label class="randomClass">1</label>
        <label class="randomClass">2</label>
        <label class="randomClass">3</label>
        <label class="randomClass">4</label>
        <label class="randomClass">5</label>
        <label class="randomClass">6</label>
        <label class="randomClass">7</label>
        <label class="randomClass">8</label>
        <label class="randomClass">9</label>
        <label class="randomClass">10</label>
        <label class="randomClass">11</label>
        <label class="randomClass">12</label>
        <label class="randomClass">13</label>
        <label class="randomClass">14</label>
        <label class="randomClass">15</label>
        <label class="randomClass">16</label>
    </div>
</div>
<button id="move">Move</button>

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

Trigger a pop up using AJAX when successful

There is a button that, when clicked, triggers a pop up dialog box with the code below: <div class="button-wrap"><button data-dialog="somedialog" class="trigger">Open Dialog</button></div> The script responsible for activating the ...

Tricks for preventing axios from caching in GET requests

I am utilizing axios in my React-Native application Firstly, I set up the headers function setupHeaders() { // After testing all three lines below, none of them worked axios.defaults.headers.common["Pragma"] = "no-cache"; axios.defaults.heade ...

Problem with JavaScript and Basic HTML5 Canvas

I'm trying to dive into learning about using a canvas, but I just can't seem to get this basic code to work. Does anyone know what I might be doing wrong? Link to jsfiddle <canvas id="ctx" width="500" height="500" style="border:1px solid #00 ...

The array value remains unchanged when included in the response

My goal is to send back the "projets" array within an expressJs route after fetching images for each item. However, when I return the response with the updated array, the newly added fields don't seem to be included. Note: When I log the added item, ...

The script was denied execution due to the non-executable MIME type ('text/html') and the activation of strict MIME type checking

I'm currently attempting to retrieve data from the forismatic API, but I'm not receiving any response. I'm using AJAX in jQuery, however, I keep encountering the following error in my console: The script at '' was refused to execu ...

I'm curious if there is a git command available that displays commit messages alongside the corresponding source code in a clear and understandable format

Is there a user-friendly interface available for git-annotate, or do you have to manually handle it yourself? I'm searching for a tool that utilizes plain git-annotate or git-annotate --porcelain to generate an HTML (or TeX or RTF) file with two colum ...

The website takes forever to load on Internet Explorer and it keeps freezing

When attempting to access a certain website, there is a noticeable delay before the page actually loads (especially when using older versions of Internet Explorer). The issue does not occur with other web browsers. The website in question is a simple Word ...

What is the best way to divide widgets in a Wordpress Sidebar?

I am looking to customize the spacing between widgets in my Wordpress sidebar, similar to what is shown on this example site. Currently, my sidebar does not have the desired spacing. I have tried various CSS codes found online, but none of them seem to be ...

Building a card carousel component in Vue JS

Struggling with creating a unique card slider using Vue JS? After exploring npm packages like Vue Carousel 3D and Vue Slick, I haven't found the ideal slider for my project. My specific card slider setup is showcased below: https://i.sstatic.net/GiNc ...

What is the best way to position content at the bottom of a div?

I've been attempting to align my menu div with the bottom of my logo div on the same line within my header section. <div id="header"> <div id="top-bar"> </div> <div id="clear"></div> ...

Anticipate feedback from Python script in Node.js

I have developed a website using nodejs and express, but I am facing an issue with integrating a python script for face recognition. The problem lies in the fact that when I invoke this script from nodejs using child-process, it takes around 10 to 20 secon ...

Sort through an array of objects using a different array

I am looking to showcase projects based on specific skills. For instance, if I choose "HTML", I want to see all projects that have "HTML" listed in their array of skills. If I select multiple skills, then only display projects that have those exact skills. ...

Utilizing Ant Design Icons without an Internet Connection

In my current project, a reactJS application utilizing ant design for the UI was recently deployed to production on locked down computers. These computers lack internet access, causing ant design icons on modals to appear as empty boxes. Upon investigation ...

Tips for Keeping a Responsive Image at the Forefront of a Text-Image Layout as You Scroll

I'm currently in the process of creating a website where text appears on the left side with an accompanying image on the right. The challenge I'm encountering is ensuring that as users scroll, the image adjusts dynamically based on the associated ...

The Next Js 13 API route is failing to retrieve accurate data following a post request

I've been working on a project involving authentication using Django backend and Next.js frontend. For state management, I'm utilizing Redux Toolkit. However, I've encountered an issue with the Next.js API that communicates data to the backe ...

Tips for aligning a form in the middle using Bootstrap 4.1

Hi, I'm new to the world of Front End development and I have a question about centering a form. I tried using the 'mx-auto' class in Bootstrap 4.1.0 documentation, but it didn't work as expected. My lead informed me that this isn&apos ...

How can I determine the Windows service pack version directly from my web browser?

Is there a method to determine the installed service pack from the browser? It doesn't seem to be available in System.Web.HttpBrowserCapabilities in asp.net. I am looking for a solution to alert users about the necessity of updating to XP Service Pack ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...

Two consecutive instances of the outcome recorded in the ajax table

I am trying to add data to a table, but one of my results is appearing twice. Here is the JSON response I received: groupname […] 0 {…} survey_id 2 group_name DEMO 1 {…} survey_id 1 group_name TEST This is what my AJAX success function ...

Issues with prop passing from parent to child component in NuxtJs

This is my "index.vue" page located in the "blogs" folder within the pages directory. <template> <blog-grid :v-if="blogsList.length>0" :v-for="item in blogsList" :item="item"></blog-grid> </template&g ...