Skipping every third index in a JQuery .each loop after removing an element

I have a project where I need to display elements in rows of 4, and when an element is deleted, I want the remaining elements to shift up. To achieve this, I am currently assigning a class "last" to every fourth item after a deletion and inserting a spacer div below the row (after the last element).

Check out the fiddle here: http://jsfiddle.net/yNA4J/1/

Here's the code snippet:

HTML:

<section class="Con1Artists" id="show">
    <article class="topHeadingTitle">
      <article class="vieAllTitle"><a id="show2" href="#"><span>View All</span></a></article>
    </article>

    [....]

    </article>
  </section> 

CSS:

.MusicianCol {
display: block;
margin: 0 0 50px;
}

.boxBg {
background: #fff;
border-radius: 6px;
box-shadow: 1px 2px 1px 0 rgba(0, 0, 0, 0.1);
-moz-box-shadow: 1px 2px 1px 0 rgba(0, 0, 0, 0.1);
-webkit-box-shadow: 1px 2px 1px 0 rgba(0, 0, 0, 0.1);
margin: 0 3% 0 0;
width: 22%;
float: left;
}

[....]

JQuery:

//Remove artist
$(".remove-artist").click(function(event) {

      event.preventDefault();

      var id = $(this).find("i.fa-times").attr('id');

      var likeid = id.replace( /^\D+/g, '');

      $("#box-"+likeid).hide('slow', function() { 

          $("#box-"+likeid).remove(); 
          $('.spacer').remove();

          $('.boxBg').each(function() {
              $(this).removeClass('last');

              console.log($(this).index());
              console.log($(this).attr('id'));

              if (($(this).index() + 1) % 4 == 0){

                $(this).addClass('last');
                $('<div class="spacer"></div>').insertAfter($(this));
              }


          });

      });

});

//Show more artists
$('#show2').click(function(event){

    if($(this).hasClass('showing')) {
      $(this).removeClass('showing');
      $('.past').hide();
      $('.spacer').remove();
      $(this).find('span').html("View All");
    }
    else {
      $(this).addClass('showing');
      $('.past').show();

      $('<div class="spacer"></div>').insertAfter($('.last'));
      $(this).find('span').html("View Less");
    }
    event.preventDefault();
});

However, while testing with 16 elements and deleting the 8th one, the console.log($(this).index()) results were not as expected:

0
1
2
3
5
6
7
9
10
11
13
14
15
17
18

An issue arises where it skips an index after the first row for every third element, leading to rows of 3 instead of 4 being displayed. Can anyone identify what might be causing this problem? Your assistance is appreciated.

Answer №1

When you add a sibling element, it impacts the outcome of $(this).index() for all future iterations. Fortunately, $(this).index() is not actually necessary.

$('.boxBg').each(function(i) {
    $(this).removeClass('last');

    console.log(i);
    console.log($(this).attr('id'));

    if ((i + 1) % 4 == 0){
        $(this).addClass('last');
        $('<div class="spacer"></div>').insertAfter($(this));
    }
});

This can be simplified into a single line using implicit iteration and filtering. Just make sure to remove the spacer beforehand and ensure that the boxBg divs are the only elements in the parent div.

$(".boxBg").removeClass('last').filter(':nth-child(4n)').addClass('last').after('<div class="spacer"></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

Mastering the Art of Customizing Styling in Ant Design

I'm currently working with a table from Ant Design, but I'm facing an issue where the padding or margin applied by the Ant Design CSS is preventing the table from expanding on the left side. The table has an inline CSS of table layout: auto which ...

What are some effective strategies for enhancing the performance of React user interfaces?

I'm currently dealing with a performance challenge in one of my React applications. What are some best practices to enhance the responsiveness of the User Interface? One approach could be to minimize the usage of conditional expressions like { carIsR ...

A guide to determining the dimensions (width, height, length) of a mesh using THREE.js

I've been scouring different sources in hopes of finding a way to obtain the width and height of a mesh, but I haven't had any luck. I have imported a collada model into my project, and all I need is to determine its dimensions in Webgl/Three.js ...

The $timeout function in AngularJS seems to be malfunctioning

I'm attempting to add a delayed effect to my view. After a button is clicked, a message is displayed, but I want it to disappear after 2000ms. I have tried implementing a $timeout function based on recommendations I found, but it doesn't seem to ...

Create a circular status button that overlays on top of another element using CSS

Looking to enhance my CSS skills! Seeking advice on creating a status button that changes color based on chat availability and positioning it on top of another button. ...

Is it possible to customize the default styling options in Tailwind?

I am currently working on a blog using NextJS, and I have encountered an issue with Tailwind's list style type. It seems that the default styling for list style type is set to list-none, resulting in my <ul> <li> elements not being styled ...

SEO tip: concealing lightbox images from search engines

Our website primarily uses lightboxes loaded via Ajax for images, meaning search engines may not index them when crawling the page. Is there a way to enhance SEO for these lightbox images? Thanks for your help! ...

insert data into modal's interface

I'm encountering an issue with my code, where the modal is not displaying the values inside the brackets as if they were not bound correctly. Everything else in the ng-repeat seems to be working fine, but for some reason the values are not being displ ...

Having trouble updating the route with the $location service, even after attempting to use $scope.apply

After trying to utilize the location service with no success, I am left wondering why my view isn't changing even after using either $scope.$apply() or $scope.apply. Prior to posting my question, I conducted thorough research on similar inquiries but ...

Tips for making a table have the same width as its child td elements and enabling the table to exceed the width of the viewport

I am facing a challenge with a table that has dynamically changing rows and columns. <table> <tr> <td>column 1</td> <td>column 2</td> <td>column 3</td> </tr> <tr> <td> ...

"The issue of a Cordova app experiencing timeouts while attempting to connect to a local server via

I've been searching tirelessly to find a solution to this issue, but so far I've had no luck. My problem involves trying to establish a connection between a Phonegap app and a server hosted on my local machine, but every time it times out. I foll ...

Problem with MongoDB - increasing number of connections

I have encountered an issue with my current approach to connecting to MongoDB. The method I am using is outlined below: import { Db, MongoClient } from "mongodb"; let cachedConnection: { client: MongoClient; db: Db } | null = null; export asyn ...

Retrieving multiple raw markdown files from GitHub using React JS

Currently, I am facing a challenge in fetching data from multiple raw .md files stored in different folders within a GitHub repository. Although I have successfully retrieved data from one file, my goal is to access all of them. The situation involves a G ...

Adjusting the format of a JavaScript object

Looking at the object below: {A: 52, B: 33} I want to transform it into this format: ["A", 52], ["B", 33] Any recommendations on how to achieve this conversion? ...

Transform the input value into a string

Struggling with converting an input value into a string. HTML: <input type="text" placeholder="Email Ex: john123" id="emailinput"> <input type="text" placeholder="Domain Ex: @gmail.com" id="domaininput"> JS: let emailVal = document.getElem ...

What is the most effective method for displaying an error code when a JavaScript error occurs?

I'm currently dealing with a library that is throwing errors: throw new Error('The connection timed out waiting for a response') This library has the potential to throw errors for various reasons, making it challenging for users to handle ...

Tips for refining search criteria with a combination of checkbox and range slider in Angular 2

In an attempt to refine the results for the array "db," I have implemented three filters: price, duration, and category. I have experimented with using the filter() method to apply these filters. You can find the code I have worked on here: https://stack ...

Unique Pie Chart Designs

As I attempt to create a dynamic arc-shaped pie graph using CSS, representing 100% of the data, I find myself facing challenges. Despite extensive research and Google searches, I have yet to come across a suitable solution. The following reference appears ...

Reload the webpage with changing data without the need to refresh the entire browser

Hello, I have been working on a project that requires refreshing data every 10 seconds. I have successfully created a separate file to load one type of information, but I am now faced with the question of how to handle 3 different sensor data in my databas ...

JavaScript Simplified Data Sorting after Reduction

I have extracted data from a JSON file and successfully condensed it to show the number of occurrences. Now, my next step is to arrange these occurrences in descending order, starting with the most frequent. To illustrate: var myData = [{ "datapo ...