kalenpw
kalenpw

Reputation: 695

javascript collapsible table without jquery

This is a simple question I can't seem to figure out and every google search returns a million ways to do this via jquery, but I'd prefer to use vanilla javascript because I am new to it and want to learn it well before using any libraries. What I am trying to do is have a button collapse part of a table when clicked and then show those hidden parts again when clicked again. Basically just toggling the display of a class of elements.

I have a button that calls the test() function when clicked nothing on my table changes. Here is my javascript code. I am using collapse[0] because if I understand it correctly collapse is a nodeList and I always close and open all of these together so I only need to check the first element.

function test() {
    var collapse = document.getElementsByClassName("catOne");
    var i = 0;//Counter for loops

    if(collapse[0].style.display === "table-row"){
        for(i = 0; i < collapse.length; i += 1){
            collapse[i].style.display = "none";
        }
    }

    if(collapse[0].style.display === "none"){
        for(i = 0; i < collapse.length; i += 1){
            collapse[i].style.display = "table-row";
        }
    }    
}

I've tested the function with this code:

function test() {
    var collapse = document.getElementsByClassName("catOne");
    var i = 0;//Counter for loops

    for (i = 0; i < collapse.length; i += 1) {
        collapse[i].style.display = "none";
    }

which works fine on collapsing the elements so evidentally the issue is with my if statement, but my IDE, Netbeans, doesn't throw any errors and as far as I can tell it should be working.

Thanks for the help.

Link to html and javascript: https://jsfiddle.net/ozjbekjy/

Upvotes: 0

Views: 3088

Answers (1)

Tieson T.
Tieson T.

Reputation: 21246

I suspect there are a few problems working against you.

First, you need to make sure the test() function is defined earlier in the page than it's being used. With jQuery, that means using the $(function(){}) wrapper to apply event handlers on DOM ready. You can approximate the same thing yourself with something like this answer.

Otherwise, simply place the <script> tag somewhere before the table (probably in the <head>), and the onclick will work.

You also are using i += 1 where you could be using i++ - they accomplish the same behavior.

Secondly, instead of manipulating the style attribute, use the classList.toggle() function to simply add and remove a class that has the rule display: none, like so:

CSS

.hide-me {
  display: none;
}

JavaScript

function test() {
  var collapse = document.getElementsByClassName("catOne");

  for (var i = 0; i < collapse.length; i++) {
    collapse[i].classList.toggle("hide-me");
  }
}

Your JSFiddle, with the suggested updates: https://jsfiddle.net/ozjbekjy/4/

Upvotes: 3

Related Questions