Certain rows in the table should maintain a consistent width, while others are allowed to vary

I am dealing with a table containing certain rows

Some of these rows are visible, while others are hidden.

The visible rows at the start are referred to as: mainTrs.

Clicking on a visible row will make all rows with a class matching its id visible.

Clicking it again will close all previously opened rows.

When invisible rows become visible, the table shifts.

I want the mainTrs to maintain the same width as its td-s.

(And the other rows should adjust accordingly).


For instance:

In the beginning, assuming this is the initial table setup:

https://i.sstatic.net/J8uML.png

These rows should retain their width when toggling.


Desirable outcomes:

https://i.sstatic.net/eSsaz.png

https://i.sstatic.net/sSTk6.png

As seen, the initial rows (red and blue) maintain the same width.

The other rows expand without affecting the red and blue ones.


Undesired outcomes:

https://i.sstatic.net/s007K.png

https://i.sstatic.net/KN2cW.png

This is problematic because the red and blue rows become wider than initially.


I attempted using max-width for the mainTrs but did not succeed.


This is an excerpt from my table:

<table>
    <tr id="a123" onclick="toggleTable(this)" data-isOpen="false">
        <td>name</td>
        <td>last name</td>
    </tr>
    <tr class="tr_a123 hidden">
        <td>this is my first cell</td>
        <td>this is my second cell</td>
    </tr>
    <tr class="tr_a123 hidden">
        <td>another text</td>
        <td>another text</td>
    </tr>
    <tr id="a456" onclick="toggleTable(this)" data-isOpen="false">
        <td>name</td>
        <td>last name</td>
    </tr>
    <tr class="tr_a456 hidden">
        <td>wow</td>
        <td>more text</td>
    </tr>
    <tr class="tr_a456 hidden">
        <td>something</td>
        <td>sometimes</td>
    </tr>
</table>

This shows the JavaScript in use:

function toggleTable(element) {
    var isNeedToShowMore = $(element).attr('data-isOpen') == "false";
    $(element).attr('data-isOpen', isNeedToShowMore);

    var elementId = $(element).attr('id');
    if (isNeedToShowMore) {
        $('tr.tr_' + elementId).show();
    }
    else {
        $('tr.tr_' + elementId).hide();
    }
}

Here is the link to my fiddle demonstration:

http://jsfiddle.net/52kj3b8m/

Answer №1

The presence of unwanted spaces in your layout is a result of using a <table>. Due to the nature of table columns, they adjust their size based on the largest content within them. This leads to consistent spacing issues when cell widths are identical. To visualize this better, add borders to the <td> elements. Alternatively, achieving the desired layout can be done with accordions.

A detailed breakdown:

In Snippet 1, you'll see how the current setup results in undesirable content presentation due to the table structure.

Snippet 2 showcases an accordion design that requires jQuery, jQuery UI, and the Dark Hive theme.

SNIPPET 1

function toggleTable(element) {
    var isNeedToShowMore = $(element).attr('data-isOpen') == "false";
    $(element).attr('data-isOpen', isNeedToShowMore);

    var elementId = $(element).attr('id');
    if (isNeedToShowMore) {
        $('tr.tr_' + elementId).show();
    }
    else {
        $('tr.tr_' + elementId).hide();
    }
}
td {
  border: 2px dashed red;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr id="a123" onclick="toggleTable(this)" data-isOpen="false">
        <td>name</td>
        <td>last name</td>
    </tr>
    <tr class="tr_a123 hidden">
        <td>this is my first cell</td>
        <td>this is my second cell</td>
    </tr>
    <tr class="tr_a123 hidden">
        <td>another text</td>
        <td>another text</td>
    </tr>
    <tr id="a456" onclick="toggleTable(this)" data-isOpen="false">
        <td>name</td>
        <td>last name</td>
    </tr>
    <tr class="tr_a456 hidden">
        <td>wow</td>
        <td>more text</td>
    </tr>
    <tr class="tr_a456 hidden">
        <td>something</td>
        <td>sometimes</td>
    </tr>
</table>

SNIPPET 2

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
  <title>Accordions</title>
  <link href='http://code.jquery.com/ui/1.12.1/themes/dark-hive/jquery-ui.css' rel='stylesheet'>
  <style>
    d
  </style>
</head>

<body>
  <header>

  </header>
  <main>
    <section class='rows'>
      <dl>
        <dt>Header 1</dt>
        <dd>
          <p>
            Yoggothog mg f'athg ep hrii orr'e 'fhalma hafh'drn phlegeth, nglui ron phlegeth mnahn' throd 'fhalma chtenff R'lyeh bug, Chaugnar Faugnnyth nog hai nw ebunma llll 'ai naYoggoth, grah'noth nwagl ph'hlirgh nog syha'h Yoggoth cya. Ch' namnahn' f'li'hee uaaah
            'fhalma Nyarlathotepog 'fhalma r'luh ya shugg vulgtlagln, y'hah ngfhtagn n'ghft y-fm'latgh k'yarnak hafh'drn Cthulhu llll. Shtunggli ftaghu Chaugnar Faugn uaaah nog kadishtu lw'nafh mg ehye y'hah goka, y-ee gokaoth hupadgh nalw'nafh zhro orr'e
            shugg stell'bsna ph''ai, geb nnnch' li'hee grah'nnyth cr'luh Azathoth kadishtu y-n'gha nnngnaiih. Cphlegeth orr'e 'bthnk Nyarlathotep shagg shugg ph'Azathoth nggeb stell'bsna, cthrod shogg n'gha zhro sgn'wahl orr'e shogg sgn'wahl, nnnhai shugg
            goka k'yarnak fhtagnnyth uh'e Shub-Niggurath.
          </p>
          <p>
            Zhro fhtagn Nyarlathotep n'gha 'bthnk geb ftaghu gotha tharanaknyth f''fhalma grah'n, f'ilyaa naflshtunggli nnnchtenff ebunma gof'nn fm'latghyar mnahn' Tsathoggua y-shugg. Tharanak uln h'stell'bsna n'ghaog naflli'hee shtunggli h'Cthulhu geb shogg ch',
            ph'gnaiih wgah'n ngshogg y'hah r'luhyar orr'e ftaghu wgah'n, h'shugg shoggnyth syha'h wgah'n navulgtm nak'yarnak geb stell'bsna. Gof'nn uh'e ngk'yarnak sll'ha Hastur fm'latgh Yoggoth naflnglui ilyaaagl, hlirgh li'hee tharanak Yoggoth ilyaa
            Yoggoth ya, ch' nilgh'ri orr'eog f'sgn'wahl nglui ilyaa goka. Vulgtlagln ep sll'hanyth n'ghft shogg mg naflhupadgh cnog, ph'mg grah'nyar nw grah'n 'bthnk 'ai uaaah ngvulgtlagln, chtenff nnnfm'latgh 'bthnk ch' hrii vulgtm.
          </p>
          <p>
            Lloig nog zhro 'bthnk R'lyeh 'fhalma nglui sll'ha uln, bug Yoggoth epyar stell'bsna shugg ebunma nnnorr'e, chrii h'syha'h sll'ha lloig f'wgah'n ph'gotha hlirgh. Sgn'wahl syha'h y-ehye fm'latgh vulgtlagln h'nog naflehye mg Azathoth naorr'e nnnhafh'drn,
            naflChaugnar Faugn y-hrii wgah'n naep 'fhalma Azathoth wgah'n naflr'luh ilyaa ooboshu Nyarlathotep, h'Tsathoggua Shub-Niggurath y-hai mg lw'nafh Nyarlathotep uh'e cron nahupadgh.
          </p>
        </dd>

        <dt>Header 2</dt>
        <dd>
          <iframe id='ifrm1' name='ifrm1' src='http://w3schools.com' width='90%'></iframe>
        </dd>

        <dt>Header 3</dt>
        <dd>
          <video id="vid1" class="vid" src="http://html5demos.com/assets/dizzy.mp4" width='500' controls></video>
        </dd>

      </dl>
    </section>
  </main>
  <footer>

  </footer>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script>
    $(function() {
      $('.rows').accordion({
        collapsible: true,
        header: 'dt',
        heightStyle: 'content',
        active: false
      });
    });
  </script>
</body>

</html>

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

"By simply pressing the back button, Material UI Table effortlessly expands the row limit to accommodate

After creating a Material UI table and implementing Pagination, I noticed that the row limit increases automatically when clicking the back button. Even after consulting the Material UI docs, it seems like others are facing the same issue. Can anyone provi ...

Creating a Piechart in Kendo UI that is bound to hierarchal remote data

I am facing an issue with binding remote data to a pie chart while managing a grid with dropdown sorting options. The grid is working fine, but I am unable to display the hierarchical data on the pie chart as categories. <!DOCTYPE html> <html> ...

Is there a way to add 100 headings to a webpage without using a loop when the page loads

Just joining this platform, so please be patient with me! The task at hand is to insert 100 h3 headings on page load ("Accusation 1, Accusation 2, Accusation 3,...Accusation 100"). We are restricted to using only 1 loop throughout the lab, which will also ...

jQuery concealing selections from dropdown menus

Is there a way to use jquery sort to order dropdown list options and hide the "select" item in the dropdown? Check out my fiddle code here <select id="mySelect"> <option value="">select</option> <option value="1">a</opt ...

Navigating through Index in #each in emberjs

Take a look at the code provided below: http://jsbin.com/atuBaXE/2/ I am attempting to access the index using {{@index}}, but it doesn't seem to be compiling. I believe that handlebars should support this feature: {{#each item in model}} {{@index} ...

Wrapping text around an image using two distinct Angular components

Can text wrap around an image in Angular even if they are in separate components? Or do the text and image have to be within the same component for this to work, regardless of whether the image is on the left or right side? https://i.stack.imgur.com/hdlxD ...

JavaScript change the object into a string

I've been working on code to convert strings into dictionaries and arrays, and vice versa. While string to array and string to object conversions are successful, the reverse process is giving me trouble. I'm currently stuck and unsure of how to r ...

Guide on converting a GraphQL request string into an object

Seeking assistance with intercepting and parsing GraphQL queries/mutations from a POST request body in an Apollo lambda server environment running on Node.js. The requests do not come in JSON format, but as GraphQL query language. I have been unable to fi ...

Joomla website experiencing issues with Bootstrap popover functionality

Just wanted to share that I am currently working on this page: I found an example that inspired me from here: I have a feeling that Joomla might be including a resource that is causing conflicts with the popover not showing. This is the code snippet I h ...

IE rendering issue: jQuery image slideshow captions lack transparency

I recently created a slideshow using jQuery that features fading images with corresponding captions in individual divs. While the captions are meant to have a transparent appearance, I have encountered an issue specifically in Internet Explorer where this ...

Aligning the Bootstrap 5 navbar dropdown to the right side

I'm having trouble getting a part of my navbar to align right in bootstrap 5. I've followed the new documentation, but I think I might be adding the text in the wrong place. Can someone assist me in moving my dropdown to the right side of the nav ...

Having trouble with the jQuery function not working as expected? Can't seem to identify any errors in the code?

I'm attempting to capture the essence of moving clouds from this beautiful theme: (I purchased it on themeforest, but it's originally designed for tumblr) Now, I want to incorporate it into my wordpress website here: The code used to be under ...

Tips for eliminating unwanted white space that appears after clicking on a drop-down menu

Is there a way to remove the white space after clicking on the drop down menu? <select name="shipping_method" class="required-entry" id="shipping_method" style="width:250px;"> <optgroup disabled="disabled" style="font-style: normal; display: n ...

bootstrap modal opens but remains hidden

I seem to be encountering an issue with the Bootstrap modal. The modal opens up, but for some reason it is not visible on the screen. Oddly enough, all the elements are present within the modal. Below is the code snippet: <button type="button" data-to ...

Retrieve the prior position using the AngularJS ui-router

Utilizing fromState and fromParams within the $stateChangeSuccess event allows us to access all details regarding the previous location. This concept is elaborated in the following discussion: Angular - ui-router get previous state $rootScope.$on('$s ...

Deciphering the LocalDate and nested object array in an AJAX response

Seeking assistance, looking for solutions to two problems. Firstly, how can I display LocalDate in an ajax response? And secondly, how do I iterate over a list of Custom objects received in the ajax response? I am passing a List of Custom Objects and Loca ...

Using the power of jQuery, execute a function only once when the element is clicked

My goal is to use jQuery's .one method to change the color of an element only once, even if clicked again. However, I am having trouble getting it to work properly. Here is my HTML: <!DOCTYPE html> <head> <meta charset="UTF-8"& ...

How can you use a selector to filter Cheerio objects within an `each` loop?

As I work on parsing a basic webpage using Cheerio, I began to wonder about the possibilities at hand: Consider a content structure like this: <tr class="human"> <td class="event"><a>event1</a></td> <td class="nam ...

Struggling to delete a specific item by its ID from MongoDB within a Next.js application

Currently, I am building a todo app in nextjs to enhance my skills. However, I'm encountering some difficulties in deleting single todos from the database using the deleteOne function. Below is the frontend call: async function deleteTodo(id) { a ...

Generating a Stream for FormData implementation

I am currently utilizing an API to import a CSV file. The CSV file is generated in memory from a String and then uploaded using the request module. However, I am encountering difficulties in creating a Readable Stream from the String. To resolve this issue ...