Clicking on an unspecified amount of elements toggles multiple elements in JavaScript

I am currently working on a table that requires an undefined number of rows, each displaying a set number of elements when clicked. I have managed to achieve this functionality for a predetermined number of elements, but I am seeking a solution to make it work dynamically.

Check out the working code on jsfiddle.net

Here is a snippet of the jQuery code I have so far:

$('.warning').on('click', function(e) {
  var $ele = $(this).nextUntil('.warning').find('td > div');
    $ele.slideToggle();
  });
});

The goal is for each clicked row in the table to display three corresponding div elements. While I prefer a jQuery solution, I am open to vanilla JavaScript implementations as well.

UPDATE: Apologies for omitting the requirement for a sliding animation. The current toggle method does not provide the desired effect.

UPDATE2: Thank you, Terry, for the recommendation. The fiddle has been revised with the updated working code.

Answer №1

We can simplify your table row markup by hiding some elements:

<tr class="hidden">
  <td>
    <div>Hidden.</div>
  </td>
  <td>
    <div>Hidden.</div>
  </td>
  <td>
    <div>Hidden.</div>
  </td>
</tr>

...and you can achieve this with jQuery:

  1. Use .nextUntil('.warning') to select the trailing <tr> after each .warning element
  2. Utilize .slideToggle() for smooth show/hide animations

Here is the jQuery code implementing the logic above:

$('.warning').on('click', function() {
    var $ele = $(this).nextUntil('.warning').find('td > div');
    $ele.slideToggle();
});

If you only want to target downstream <tr> that has the class hidden, add a filter like this:

$('.warning').on('click', function() {
  var $ele = $(this).nextUntil('.warning').filter(function() {
    return $(this).hasClass('hidden');
  }).find('td > div');
  $ele.slideToggle();
});

Note that using this method may result in stacked borders when hiding elements, as the table rows are not collapsed.

Check out the example below:

$(function() {
  $('.warning').on('click', function() {
    var $ele = $(this).nextUntil('.warning').filter(function() {
      return $(this).hasClass('hidden');
    }).find('td > div');
    $ele.slideToggle();
  });
});
table {
  width: 75%;
  border-collapse: collapse;
}

tr,
td {
  border: 2px solid #AEAEAE;
  padding: 0;
}

td {
  width: 50px;
}

.hidden td div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
  <tbody>
    <tr class="warning">
      <td>Click to show</td>
      <td>Name</td>
      <td>Age</td>
    </tr>
    <tr class="hidden">
      <td>
        <div>Hidden.</div>
      </td>
      <td>
        <div>Hidden.</div>
      </td>
      <td>
        <div>Hidden.</div>
      </td>
    </tr>
    <tr class="hidden">
      ...
    </tr>

    ...
    
  </tbody>
</table>

Answer №2

Take a look at the snippet below, where I've applied the 'hidden' class to all elements instead of naming them differently:

$(".warning").on("click",function(){
  $(this).nextUntil(".warning").find(".hidden").slideToggle();
})
table {
  width: 75%;
  border-collapse: collapse;
}
tr, td {
  border: 2px solid #AEAEAE;
  padding: 0;
}

td {
  width: 50px;
}

.hidden, .hidden1, .hidden2 {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
      <tbody>
        <tr class="warning">
          <td>Click to show</td> <td>Name</td> <td>Age</td>
        </tr>
        <tr class="active">
          <td>
              <div class="hidden">Hidden.</div>
          </td>
          <td>
              <div class="hidden">Hidden.</div>
          </td>
          <td>
              <div class="hidden">Hidden.</div>
          </td>
        </tr>
        <tr class="active">
          <td>
              <div class="hidden">Hidden.</div>
          </td>
          <td>
              <div class="hidden">Hidden.</div>
          </td>
          <td>
              <div class="hidden">Hidden.</div>
          </td>
        </tr>
        <tr class="warning">
          <td>Click to show</td> <td>Name</td> <td>Age</td>
        </tr>
        <tr class="active">
          <td>
              <div class="hidden">Hidden.</div>
          </td>
          <td>
              <div class="hidden">Hidden.</div>
          </td>
          <td>
              <div class="hidden">Hidden.</div>
          </td>
        </tr>

        <tr class="warning">
          <td>Click to show</td> <td>Name</td> <td>Age</td>
        </tr>
        <tr class="active">
          <td>
              <div class="hidden">Hidden.</div>
          </td>
          <td>
              <div class="hidden">Hidden.</div>
          </td>
          <td>
              <div class="hidden">Hidden.</div>
          </td>
        </tr>
      </tbody>
    </table>

Answer №3

When you use jQuery's <code>.on method with the event "click" on a target element with class ".warning", it will add the event to dynamic elements that may be generated in the future.

To achieve the desired effect, find the next hidden element and toggle its visibility.

Here is an example:

$(".warning").on("click", function() {
  var nextHidden = $(this).next('.hidden');
  nextHidden.find('div').slideToggle();
});
table {
  width: 75%;
  border-collapse: collapse;
}

tr,
td {
  border: 2px solid #AEAEAE;
  padding: 0;
}

td {
  width: 50px;
}

.hidden div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
  <tbody>
    <tr class="warning">
      <td>Click to show</td>
      <td>Name</td>
      <td>Age</td>
    </tr>
    <tr class="active hidden">
      <td>
        <div class="">Hidden.</div>
      </td>
      <td>
        <div class="">Hidden.</div>
      </td>
      <td>
        <div class="">Hidden.</div>
      </td>
    </tr>

    <tr class="warning">
      <td>Click to show</td>
      <td>Name</td>
      <td>Age</td>
    </tr>
    <tr class="active hidden">
      <td>
        <div class="">Hidden.</div>
      </td>
      <td>
        <div class="">Hidden.</div>
      </td>
      <td>
        <div class="">Hidden.</div>
      </td>
    </tr>

    <tr class="warning">
      <td>Click to show</td>
      <td>Name</td>
      <td>Age</td>
    </tr>
    <tr class="active hidden">
      <td>
        <div class="">Hidden.</div>
      </td>
      <td>
        <div class="">Hidden.</div>
      </td>
      <td>
        <div class="">Hidden.</div>
      </td>
    </tr>
  </tbody>
</table>

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

Is there a way to disable a JavaScript hover effect when the mouse moves away?

I came across this JavaScript code that swaps the background of a parent div when clicking on a link in a child div. However, I noticed that the hover state remains even after moving the mouse out of the link. Can someone help me modify the code so that ...

Step-by-step guide to setting up Angular 2 with fullpage.js scrolloverflow

I am currently working on a project using Angular 2 that incorporates the fullpage.js port from https://github.com/meiblorn/ngx-fullpage. I am facing an issue with implementing scrolloverflow on a specific section and could use some guidance. I have alread ...

Struggling to configure an input field using ExtJS

I am trying to use an onChange event to update an input field with the selected option. Below is my code: HTML: <select id="builds" onchange="setBuild()"> <option value="select">Select</option> ... </select> <input ty ...

Utilizing an array as a child component in conditional rendering with vue.js

I have a Laravel API and the front end is built with Vue.js + Laravel. I am fetching data from the API and passing it to the view. Now, I want to implement conditional rendering based on certain criteria. Here's what my array looks like: "data" =&g ...

Tips for managing serverside validation and clientside validation in your web application

Utilizing both clientside and serverside validation in ASP.NET controls is crucial for ensuring usability and security. While simple validations like length checks or regular expressions are easy to implement and maintain, more complex validations can beco ...

What is the best way to utilize document.body in order to add a table to a designated DIV?

Once I make a copy of the table, my goal is to insert this new table into a designated DIV named div1. How can I add the new table to div1? <div id="div1"> </div> var copiedElement = document.getElementsByTagName("table" ...

Locate the closest point among a set of coordinates to a specified point

I have a situation where I have an object that contains latitude and longitude attributes. My goal is to find the closest match in an array of similar objects by considering both latitude and longitude. obj = {latitude: 55.87, longitude: 4.20} [ { & ...

Having trouble retrieving coordinates from AJAX request to Google Maps API?

I am currently developing a weather application and one of the initial steps is to retrieve the longitude and latitude coordinates for a specific city based on its name. To achieve this, I am utilizing Google Maps API to gather the necessary information. ...

What are the various ways to incorporate an image into a Vue project?

I've been struggling to insert an image, but none of the methods seem to be working. Check out this StackBlitz for more details <template> <div> <a href="#" class="header__top-item facebook" :style="image"></a> ...

Modifying various items depending on the variable's value

I'm attempting to adjust various variables depending on which button the user clicks. For instance, there are three buttons: <button id="button1" onclick="isClicked(this.id)">B1</button> <button id="button2" onclick="isClicked(this.id) ...

Tips for positioning a grid at the center of a MaterialUI layout

I am struggling to position 3 paper elements in the center of both the vertical and horizontal axes on the screen. Despite applying various CSS rules and properties, the height of the HTML element consistently shows as 76 pixels when inspected in the con ...

What is the best way to combine a new object with an existing array of objects in JavaScript?

https://i.sstatic.net/QIRzO.png Here is an array that I need to modify by adding the object {"temperature":{"work":30,"home":24}} to the beginning: 0 : {title : "tptp", {"temperature":{"work":30,"home":24}}, lastview:"12-12 21:2"} The code I am using is ...

When consecutive DOM elements are hidden, a message saying "Hiding N elements" will be displayed

Provided a set of elements (number unknown) where some elements should remain hidden: <div id="root"> <div> 1</div> <div class="hide"> 2</div> <div class="hide"> 3</div> <div class="hide"&g ...

Executing AJAX to run JavaScript code

My website utilizes pushState for page loading. I am facing an issue where I want to incorporate JavaScript on a specific page, but the content is loaded via AJAX which prevents the script from functioning as intended. How can I resolve this situation? I h ...

Tips for avoiding the display of the overall scrollbar while utilizing grid with an overflow:

In my react-redux application, I am utilizing the material ui Grid component for layout design. The structure of my code is as follows: <div> <Grid container direction="row" spacing={1}> <Grid item xs={3}> ...

Is it impossible to create links to any Django admin templates other than index.html?

Currently working on setting up a link that directs users to Django's admin/auth/user/add/ in order to allow them to create a new account for logging in. However, I have encountered an issue where setting href="{% url 'admin:index' %}& ...

VueJS Router error: The variable $route is undefined

Check out my component: const Vue = require("vue/dist/vue.js"); const qs = require("querystring"); module.exports = Vue.component("Page",function(resolve){ console.log(pageRoute); let id = pageRoute.params.id; fetch("/getPage.json",{ ...

After upgrading from Windows 7 to Windows 10, I noticed that the CSS, HTML, and Bootstrap elements seemed to have lost their impact

<!DOCTYPE html> <html> <head> <title>Registration</title> <link rel="stylesheet" type="text/css" href="styles.css"> <link rel="stylesheet" type="text/css" href="bootstrap.css"> <link href ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

Add a transition or animation effect to the <details> element as it closes

I am experimenting with adding a transition effect to the details element when it opens and closes: details { height: 1em; transition: height 2s; border: 1px solid; overflow: hidden; white-space: pre; } details[open] { height: 6em } <det ...