Get the index of the currently active element in jQuery, taking into account its position among its original sibling elements

I am implementing a function in jQuery to toggle an 'active' class on elements within a grid. Here is the code snippet:

$(".cinema-seats .seat").on("click", function () {
    $(this).toggleClass("active");
}

Essentially, when clicking on random boxes in a 3x3 grid, they are assigned the 'active' class. What I aim to achieve next is to determine the index of these active boxes in relation to the original grid.

For instance,

   box 1(active)       box2             box3
   box 4               box5(active)     box6
   box 7               box8             box9

The expected output would be 1,5 as they represent the indexes of the active classes within the grid.

This is just a simple illustration; my ultimate goal is to replicate this behavior in a larger 7x14 grid, organized into rows and columns, with all elements sharing the common class '.seats'. Once again, the objective is to retrieve the index (n-th child) of the active boxes with respect to all seats.

View the project on Codepen - https://codepen.io/divi7/pen/zYvbbVN

Answer №1

If you're looking to implement this functionality, consider following this approach:

$(".cinema-seats .seat").on("click", function() {
      $(this).toggleClass("active");
      let active = $(".cinema-seats .seat.active");
      active.each(function() {
        console.log($(this).index() + 1);
      });
    });
.seat {
      float: left;
      padding: 10px;
    }
    .seat:nth-of-type(3n + 1) {
      clear: left;
    }
    .active {
      color: red;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="cinema-seats">
      <div class="seat">
        box 1
      </div>
      <div class="seat">
        box 2
      </div>
      <div class="seat">
        box 3
      </div>
      <div class="seat">
        box 4
      </div>
      <div class="seat">
        box 5
      </div>
      <div class="seat">
        box 6
      </div>
      <div class="seat">
        box 7
      </div>
      <div class="seat">
        box 8
      </div>
      <div class="seat">
        box 9
      </div>
    </div>

To show an array of all active seats in the console output:

 $(".cinema-seats .seat").on("click", function() {
    let seats = [];
    $(this).toggleClass("active");
    let active = $(".cinema-seats .seat.active");
    active.each(function() {
      seats.push($(this).index() + 1);
      console.log(seats);
    });
 });

For better compatibility with the shared markup in the question, here's an adjusted version of the code snippet:

$(".cinema-seats .seat").on("click", function () {
      $(this).toggleClass("active");
      let seats = [];
      let active = $(".seat.active");
      active.each(function() {
        let seatsPerRow = $(this).parent().find(".seat").length;   
        if (!$(this).closest(".cinema-seats").hasClass("right")) {
          let prevRows = $(this).parent(".cinema-row").prevAll(".cinema-row").length - 1;
          seats.push($(this).index() + (seatsPerRow * prevRows));
          console.log(seats);
        } else {
          let leftSeats = $(".left").find(".seat").length;
          let prevRows = $(this).parent(".cinema-row").prevAll(".cinema-row").length;
          seats.push($(this).index() + leftSeats + (seatsPerRow * prevRows));
          console.log(seats);
        }
      });
      var bookedSeats = document.querySelectorAll(".active").length;
      var yahan = document.querySelector(".booked");
      yahan.innerHTML = bookedSeats + " Booked";
    });

    /* CSS styling for the cinema layout */
    
    body {
      margin: 60px;
      background: #111;
    }

    .theatre {
      display: flex;
      position: absolute;
      top: 70%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
      
    /* Add your custom styles here */

    
/* Include necessary libraries and set up the cinema seating arrangement */

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

Visualizing live data streaming from MySQL

I am currently using this code to retrieve values from a database and create a basic line graph (showing response time to an alert vs. UTC time). Everything works smoothly when the data is static, but now I want to try retrieving the data in "real-time" (j ...

Prevent Click Event on Angular Mat-Button

One of the challenges I'm facing involves a column with buttons within a mat-table. These buttons need to be enabled or disabled based on a value, which is working as intended. However, a new issue arises when a user clicks on a disabled button, resul ...

The replication technique in Threejs

I am experiencing an issue while attempting to clone some Vector3 objects, as the copied clones are created with all zero values in x, y, and z. Here is an example: When I use this statement console.log(this.geometries[j].vertices[i].multiplyScalar(1)); ...

Is there a way to directly display all the content in pagination format without a print preview option?

I have been tasked with implementing a feature that involves displaying content using pagination and allowing users to print all the content at once with a single click on a print button. However, I am currently experiencing an issue where clicking the pri ...

display a discrete delete button when pressing a button within ng-bootstrap

My current setup uses ng-bootstrap with Angular4. Image https://i.sstatic.net/83UhP.png In the interface, a checkbox button is used to show responses fetched from the backend. By clicking the button, the x button disappears along with other elements belo ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

What is the best way to invoke a function in a class from a different class in Angular 6?

Below is the code snippet: import { Component, OnInit, ViewChild } from '@angular/core'; import { AuthService } from '../core/auth.service'; import { MatRadioButton, MatPaginator, MatSort, MatTableDataSource } from '@angular/mater ...

Is there a method available within the Collada loader to extract multiple meshes from the scene object?

Recently, I delved into some experimental work with Blender and the Collada Loader in three.js. Within my Blender project, I have three distinct objects, but when using the loader in three.js, I can only manipulate them as one single scene object. While ev ...

Guide to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

The onchange functionality is not functioning as expected

I've added an onchange event to the select box, but it doesn't seem to be working. Any suggestions would be greatly appreciated. Thank you in advance. HTML [<select id="notifyBy" ng-change="selectchange()" style="border:none" class="formtex ...

Sending a concealed input according to the chosen option

I'm attempting to send some hidden values to a Servlet via a form, but my goal is to only pass them if the user chooses a specific option. <!-- FORM ABOVE --> <input type="hidden" name="foo" id="foo" value="foo"> <input type="hidden ...

Images with scratches visible in Chrome

This puzzle may seem easy to some, but it's been quite challenging for me. I've encountered a discrepancy in how Firefox and Chrome render images (specifically technical drawings). Despite my attempts to use image-rendering: -webkit-optimize-cont ...

Guide on utilizing loader.load() function to load a compressed file in three.js - Instructions on loading filename.json.gz

I've already compressed a file into a .gz file and stored it in S3. You can find it here: However, when I attempt to load it in Three.js using loader.load("https://oic-accounts.s3.ap-south-1.amazonaws.com/3d-try-json-files/gzip/3.json.gz", ...

How can you modify two distinct append values individually in AngularJS?

I am facing a challenge with two-way binding. I want to be able to change the name of each appended value from the displayed field options. When I try to append two additional fields, I am unable to change the name of each multiple field from the single fi ...

Is there a way to minimize the use of .value in Vue 3?

After recently diving into Vue 3, I find myself struggling to grasp some key concepts of the composition API. My current challenge involves converting a library from Vue 2 to Vue 3, where a reactive property named layout is being passed down to child compo ...

Tabindex issue arises due to a conflict between Alertify and Bootstrap 4 modal

When trying to call an Alertify Confirmation dialog within a running Bootstrap 4 Modal, I encountered an issue with the tab focus. It seems to be stuck in the last element and not working as expected. I suspect that this might have something to do with th ...

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

Efficiently finding a group of substrings within a JavaScript string

I am currently working on a method to efficiently search for specific substrings within a given string. Here is my current implementation: const apple = "apple" const banana = "banana" const chickoo = "chickoo" const dates = & ...

Sorting tables in Vue.js with Buefy components for a user-friendly experience

In my current project, I am utilizing Vue.js. The majority of the tables I am working with use Buefy's built-in sorting feature, which I find to be the simplest solution. You can find more details in the documentation here: <template> < ...

Adjusting the height of a flexbox column to fit three rows within the space of two

Exploring the wonders of Flexbox and delving into its functionality. I have shared a Code Sandbox link showcasing my React /bootstrap code in progress... Currently, I am developing a clock component with two buttons for adjusting time (increase/decrease). ...