mpasd
mpasd

Reputation: 59

Make one table row disappear when clicking another

I actually want to do a couple of things and i can't find anything similar that is javascript and not jQuery.
Updated fiddle with working code. Thanks to LuudJacobs.
I know, it's stupid.. It's just for practice, i'm new to this. It is also not finished.
So, what i want to do is:
- If "Primo Victoria" row is open, close it when "Attero Dominatus", or any other row is clicked/opened. But Show lyrics should be allowed to have as many instances open as the user wants.
- Make "Show Lyrics" text turn into "Hide Lyrics" when clicked.
I actually almost got this one, but instead of changing text, i made a new link...

document.getElementsByClassName("lyrics")[0].onclick = function () {
  var x = document.getElementsByClassName("showLyrics")[0];
  var y = document.getElementsByClassName("lyrics")[0];
    if (x.style.display === "none" || x.style.display === "") {
      x.style.display = "table-row";
      y.innerHTML = '<a href="#" class="lyrics">Hide Lyrics</a>';
    }
    else {
      x.style.display = "none";
      y.innerHTML = '<a href="#" class="lyrics">Show Lyrics</a>'
    }

Thanks for the help.

Upvotes: 2

Views: 1265

Answers (1)

Luuuud
Luuuud

Reputation: 4439

Instead of changing the style of the table row directly, it's better to use classes and toggle those instead. That way it's easier to target 'expanded' table rows. Your code could look something like this:

/* CSS */
.showLyrics{
  display: none; /* hide table row by default */
}
.showLyrics.visible{
  display: table-row; /* show the table row */
}

Now you can use Javascript to toggle between classes:

//Javascript
document.getElementsByClassName("lyrics")[0].onclick = function(){
  var x = document.getElementsByClassName("showLyrics")[0];

  //check if the row already has a .visible class
  if(x.classList.contains('visible')){

    //hide the row if it's already visible
    x.classList.remove('visible');

    /* other stuff you want to do on hiding a table row */

  }else{

    //hide all rows which are visible (have class .visible)
    var visibleRows = document.querySelectorAll('.visible'),
        i, l = visibleRows.length;

    for(i = 0; i < l; ++i){
      visibleRows[i].classList.remove('visible');
    }

    //show the row
    x.classList.add('visible');

    /* other stuff you want to do on showing a table row */

  }
}

Alternatively you can use x.classList.toggle('visible'); Read up on .classList on MDN.

As a sidenote: when I looked into your fiddle, I layed my eyes upon this: <tr class="tableEntry1, hover">. I'm pretty sure you meant <tr class="tableEntry1 hover">. Note: no comma. Classes should be separated by a space, not a comma.

Upvotes: 2

Related Questions