laker001 laker001 - 3 months ago 17
CSS Question

Show and hide table column using jQuery

I came across this fiddle from a SO answer, that hides a table column once a button is clicked. What i want is the absolute opposite. I want it to be hidden by default, and then show and hide (toggle) when i click a button.

How can i achieve this?

Here's the fiddle:

FIDDLE

HTML:

<table id="foo">
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
</table>
<button onclick='document.getElementById("foo").classList.toggle("hide2")'>Click me</button>


CSS:

#foo td {
padding: 1em;
border: 1px solid black;
}

#foo.hide2 tr > *:nth-child(2) {
display: none;
}

Answer

Set the hide2 class initially to the element or execute the toggle statement once.

#foo td {
  padding: 1em;
  border: 1px solid black;
}
#foo.hide2 tr > td:nth-child(2) {
  display: none;
}
<table id="foo" class="hide2">
  <!------------^^^^^^^^^^^-->
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
</table>
<button onclick='document.getElementById("foo").classList.toggle("hide2")'>Click me</button>