How to hide table with Javascript?

I am trying to make a hidden table. When you click a button, it should appear on the page and then when you click on that again, it should disappear. The problem is, this code is not working:

That is the function of JS

function showtable1() {
  var x = document.getElementById("table");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

This one is the HTML codes:

<body>
  <video autoplay loop muted id="backgroundv1">
    <source src="fp.mp4" type="video/mp4">
  </video>
  <div class="menü1">
    <button class="button" onclick="showtable1()">Project  1</button>
    <button class="button">Project  2</button>
    <button class="button">Project  3</button>
    <button class="button">Project  4</button>
    <button class="button">Project  5</button> 
  </div>
  <table class="table1"><td></td> <td></td> </table>
</body>

also if you need CSS code:

.table1 {
  width: 64%;
  height: 50%;
  border: 2px solid red;
  border-radius: 12px;
  margin-left: auto;
  margin-right: auto;
  transform: translate(0);
}

Upvotes: 2

Views: 19468

Answers (2)

Here you have what I think you mean. I recommend using jQuery because it facilitates your code. Any doubts let me know.

$('button').click(function(){
  if ($('table').is(':visible')) {
    $('table').hide()
  } else {
    $('table').show()
  }
})
table, th {
  border: 1px solid black;
  border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr><th>1</th><th>2</th></tr>
  <tr><th>3</th><th>4</th></tr>
</table>
<button>toggle table</button>

If you want vanilla javascript

function toggleTable() {
  var x = document.getElementById("myTable");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else { 
    x.style.display = "none";
  }
}
table, th {
  border: 1px solid black;
  border-collapse: collapse;
}
<table id="myTable">
  <tr><th>1</th><th>2</th></tr>
  <tr><th>3</th><th>4</th></tr>
</table>
<button onclick="toggleTable()">toggle table</button>

Upvotes: 4

ehab
ehab

Reputation: 8024

The problem in your code is that in the html markup, your table does not have an id, add id="table" to the table tag

replace

 <table class="table1"><td></td> <td></td> </table>

with

 <table id="table"><td></td> <td></td> </table>

and your code should work

Upvotes: 4

Related Questions