Home > Web Front-end > CSS Tutorial > How to Toggle Table Row Visibility with Header Clicks using jQuery and CSS?

How to Toggle Table Row Visibility with Header Clicks using jQuery and CSS?

DDD
Release: 2024-11-03 13:24:30
Original
390 people have browsed it

How to Toggle Table Row Visibility with Header Clicks using jQuery and CSS?

Expand and Collapse Table Rows on Header Click

This article addresses the challenge of expanding and collapsing specific table rows when the corresponding header columns are clicked.

The provided HTML table consists of rows with alternating header sections. To achieve the desired behavior, we'll leverage the power of jQuery.

jQuery Approach

  1. Identify header elements: Use the .header class to determine which table rows serve as headers.
  2. Toggle visibility: Upon clicking a header, use the nextUntil method to select all rows that follow that header until the next header is encountered. The slideToggle method then expands or collapses the selected rows.

Code Snippet

<code class="javascript">$('.header').click(function(){
    $(this).nextUntil('tr.header').slideToggle(1000);
});</code>
Copy after login

Alternative Approach Using CSS and a Pseudo-Element

  1. CSS Rule: Define a pseudo-element with the :after property to represent the expansion/collapse sign ( or -).
  2. Toggle CSS Class: Assign an 'expand' class to the clicked header and toggle its display based on the state of the pseudo-element.

Code Snippet

<code class="css">.header .sign:after{
  content:"+";
  display:inline-block;      
}
.header.expand .sign:after{
  content:"-";
}</code>
Copy after login
<code class="javascript">$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);</code>
Copy after login

This alternative approach avoids the need to track multiple CSS classes, simplifying the implementation.

The above is the detailed content of How to Toggle Table Row Visibility with Header Clicks using jQuery and CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template