1

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;
}
1
  • Do the opposite man.. Hide the columns when you create it. On the click event show it. Commented Aug 22, 2016 at 11:20

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! i was thinking it was something more complex, turns out adding the class solve it!
One question: if i want to show it when clicking a button, and then hide it again when clicking another button, how can i do it ?
@laker001 : use ...classList.add('hide2'); for hiding and ...classList.remove('hide2'); for showing :)
@laker001 : glad to help
1

I know how to do it with JQuery adding this line.

$('td:nth-child(2)').hide();

http://jsfiddle.net/bnDVS/609/

And with CSS add it:

#foo td:nth-child(2) { display: none;}

And change it:

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

To:

#foo.hide2 tr > td:nth-child(2) {
    display: table-cell;
}

http://jsfiddle.net/bnDVS/610/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.