I am facing an issue where my Javascript hide and show function is not working properly when clicked. Despite not giving

I am currently working on a Javascript onClick function to toggle the visibility of content in a lengthy table. I initially set part of the table's class to display: "none" and added a button to show the hidden content when clicked. However, nothing is rendering as expected. There are no errors displayed in the console either. Can anyone help identify the issue? Thank you.

  function myFunction() {
    var button = document.getElementById("button");
    var hidden = document.getElementsByClassName("change");

    for (var i = 0; i != hidden.length; i++) {
    if (hidden[i].style.display === 'none') {
        hidden[i].style.display === 'visible';
    } else {
      hidden[i].style.display === 'none';
    }
}};
#dates {
width: 90%;
margin: auto;
margin-top: 50px;

}

table {
width: 100%;
margin: auto;
border-bottom: 1px solid gray;
text-align: left;
}
tr td {
border-top: 1px solid gray;
margin: 5px 10px;
padding: 20px 10px;
text-align: left;
font-size: 1.3em;

}
th {
font-size: 1.5em;
padding: 10px;
}
.change {
display: none;
}

#button {
width: 25%;
padding: 15px;
margin: auto;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Mystic Mind...</title>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:600" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="css/lightbox.min.css">
   <script type="text/javascript" src="css/lightbox-plus-jquery.min.js"></script>

  <link rel="stylesheet" type="text/css" href="website gallery.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">



</head>

<section class="holder" id="dates">
  <div>
    <header>Tour Dates</header>
       <table>
          <tr>
            <th>Date</th>
            <th>Venue</th>
            <th>Location</th>
          </tr>
          <tr>
            <td>August 5, 2018</td>
            <td>Parlour</td>
            <td>Toronto, Canada</td>
          </tr>
          // more table data...
       </table>
          <div id="button">
              <button class="btn btn-outline-primary waves-effect" onclick="myFunction()">Past Dates...</button>
          </div>
   </div>
 </section>

Answer №1

It seems like the problem lies within the realm of javascript

hidden[i].style.display === 'none'
always returned empty, so instead you can utilize element.className which retrieves the class specified for that element

Therefore:

if(hidden[i].offsetWidth == 0 && hidden[i].offsetHeight == 0){}
this will return true if the element is present; else it will be false.

Here are the proposed changes:

function myFunction() {
    var button = document.getElementById("button").querySelector('button');
    var hidden = document.getElementsByClassName("change");
    for (var i = 0; i < hidden.length; i++) {
      if (hidden[i].offsetWidth == 0 && hidden[i].offsetHeight == 0) {
        hidden[i].style.setProperty("display", "table-row", "important");
        button.innerHTML = 'Show less...';
      } else {
        hidden[i].style.setProperty("display", "none", "important");
        button.innerHTML = 'Past Dates...';
      }
    }
};

function myFunction() {
    var button = document.getElementById("button").querySelector('button');
    var hidden = document.getElementsByClassName("change");
    for (var i = 0; i < hidden.length; i++) {
      if (hidden[i].offsetWidth == 0 && hidden[i].offsetHeight == 0) {
        hidden[i].style.setProperty("display", "table-row", "important");
        button.innerHTML = 'Show less...';
      } else {
        hidden[i].style.setProperty("display", "none", "important");
        button.innerHTML = 'Past Dates...';
      }
    }
};
#dates {
width: 90%;
margin: auto;
margin-top: 50px;

}

table {
width: 100%;
margin: auto;
border-bottom: 1px solid gray;
text-align: left;
}
tr td {
border-top: 1px solid gray;
margin: 5px 10px;
padding: 20px 10px;
text-align: left;
font-size: 1.3em;

}
th {
font-size: 1.5em;
padding: 10px;
}
.change {
display: none;
}

#button {
width: 25%;
padding: 15px;
margin: auto;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Mystic Mind...</title>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:600" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="css/lightbox.min.css">
   <script type="text/javascript" src="css/lightbox-plus-jquery.min.js"></script>

  <link rel="stylesheet" type="text/css" href="website gallery.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">



</head>

<section class="holder" id="dates">
  <div>
    <header>Tour Dates</header>
       <table>
          <tr>
            <th>Date</th>
            <th>Venue</th>
            <th>Location</th>
          </tr>
          <tr>
            <td>August 5, 2018</td>
            <td>Parlour</td>
            <td>Toronto, Canada</td>
          </tr>
           <!-- Truncated table data for brevity -->
      </table>
          <div id="button">
              <button class="btn btn-outline-primary waves-effect" onclick="myFunction()">Past Dates...</button>
          </div>
   </div>
 </section>

Answer №2

In your code, there is a class named .change with the style rule display: none;. It would be better to utilize this class instead of directly manipulating the style. Here's an example:

  
            function myFunction() {
                var button = document.getElementById("button");
                var hidden = document.getElementsByClassName("change");
                for(var i = 0; i < hidden.length; i++) {
                    hidden[i].classList.toggle('change');
                }
            }
        
#dates {
    width: 90%;
    margin: auto;
    margin-top: 50px;
}

table {
    width: 100%;
    margin: auto;
    border-bottom: 1px solid gray;
    text-align: left;
}
tr td {
    border-top: 1px solid gray;
    margin: 5px 10px;
    padding: 20px 10px;
    font-size: 1.3em;
    text-align: left;
}
th {
    font-size: 1.5em;
    padding: 10px;
}
.change {
    display: none;
}

#button {
    width: 25%;
    padding: 15px;
    margin: auto;
    text-align: center;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Mystic Mind...</title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:600" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="css/lightbox.min.css">
    <script type="text/javascript" src="css/lightbox-plus-jquery.min.js"></script>

    <link rel="stylesheet" type="text/css" href="website gallery.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<section class="holder" id="dates">
    <div>
        <header>Tour Dates</header>
        <table>
            <tr>
                <th>Date</th>
                <th>Venue</th>
                <th>Location</th>
            </tr>
            <!-- More table rows here -->
            <tr class="change">
                <td>November 11, 2017</td>
                <td>Buennanote</td>
                <td>Toronto, Canada</td>
            </tr>
            <!-- More table rows using the 'change' class -->
        </table>
        <div id="button">
            <button class="btn btn-outline-primary waves-effect" onclick="myFunction()">Past Dates...</button>
        </div>
    </div>
</section>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing asynchronous JavaScript code within a Golang request: a comprehensive guide

I am in need of a solution to retrieve the content from dynamically generated pages using ajax on a website, specifically with code written in golang. I have found examples for non-ajax pages but struggling to find one that works for ajax pages. Any guid ...

The functionality of the Firebase Realtime Database has ceased

After successfully developing an app with Firebase's Real-time Database for the past month, I suddenly encountered an issue today. Despite the authentication features working seamlessly, my app is no longer able to retrieve data from Firebase. It&apos ...

JavaScript and PHP are successfully displaying a success message despite the data not being saved to the database

I recently added a new feature to my website where users can submit a form using Javascript without having to reload or refresh the page. This allows for a seamless experience and displays success messages instantly. However, being a newcomer to Javascript ...

Changing dates in JavaScript / TypeScript can result in inaccurate dates being displayed after adding days

Recently, I encountered an issue with a simple code snippet that seems to produce inconsistent results. Take a look at the function below: addDays(date: Date, days: number): Date { console.log('adding ' + days + ' days'); con ...

using ng-show to display array elements

There is a syntax error showing up on the console for the code below, but it still functions as intended. Can someone help identify what I might be missing? <p class="light" data-ng-show="selectedAppType in ['A1','A2','A3' ...

Attempting to retrieve the value from a nested table within a table row using Jquery

<tr role="row" class="odd"> <td style="background-color:white"> <table> <tbody> <tr data-row-id="22"> <td id="pid"><input type="checkbox" class="sub_chk" value="8843" data-id="22">< ...

Utilizing AJAX to Fetch Data from Python

I am attempting to utilize AJAX to dynamically update a table with data retrieved from a Python script. However, when I make an AJAX request to the Python script, instead of receiving just the content within the print commands, I get the entire Python scri ...

Combining several markdown files into a unified HTML document

Is there a way to merge multiple .md files into a single HTML file? I know that Pandoc can convert .md to HTML, but I'm unsure if it's capable of converting multiple files at once. Would I need to create a program to manipulate the tool in orde ...

Tips for integrating Chart.js into my AngularJS application?

I am a beginner with AngularJS and I'm currently developing an application on Ubuntu. While trying to add Chart.js using npm install chart.js, an error is being displayed as follows. npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Tips for Guaranteeing a Distinct Email and Username are Stored in MongoDB with Mongoose

db.UserSchema = new db.Schema({ user: {type:String, unique:true, required:true,index:true}, email: {type:String, unique:true, required:true,index:true}, password: {type:String, required:true}, phon ...

Tips for using jQuery to identify the most recently modified row in an HTML table

Is there a way to identify the most recently modified (either newly added or changed) row in an HTML table? ...

Tips for adding spacing when the sidebar collapses and expands in a React application

I am attempting to achieve a layout where the body adjusts its space when the sidebar collapses and expands. Here is how it appears when the sidebar expands: see expanded sidebar here And this is how it looks when the sidebar collapses: see collapsed s ...

Discovering the geometric boundaries of a body of text

Seeking help with determining the geometric bounds of text inside hyperlinks in an InDesign document. I've tried to do this using ExtendScript but haven't had any luck. // Loop through and export hyperlinks in the document for (k = 0; k < myD ...

Guide to altering the color of a list item when hovering in HTML

Is there a way to change the color of the <li> element only when hovering over it, without affecting its parent or child elements? Here is an example: HTML: <div id="tree"> <ul> <li>apple</li> <li>banana</l ...

Tips on automatically centering an image within a div as it is resized

I'm currently working on a website that showcases cards featuring Discord users. Each card includes an avatar image within a div element, and when the user hovers over it, the image expands. However, I've noticed that as it expands, it shifts to ...

Is it possible to perform direct URL searches using react-router-dom?

Encountering an issue when attempting to directly copy a route, resulting in the following error: Error: Cannot Access / home Despite utilizing various methods such as browserHistory, I am unable to successfully render views when navigating with menu i ...

JavaScript code is functioning properly on Chrome and Internet Explorer, however, it may not be working on FireFox

Despite searching through the console, I am unable to find a solution to this issue. There are two images in play here - one is supposed to appear at specific coordinates while the other should follow the mouse cursor. However, the image intended to track ...

What is the best way to upgrade Angular from version 10 to 12?

Currently tackling an Angular project migration from version 10 to version 12. Unfortunately, the project seems to be encountering issues post-migration and is not running as expected. ...

Server encountered an unexpected T_STRING error that was not present on the localhost

While my website runs smoothly on localhost, I encounter the unexpected T_STRING error when running it on a workplace server with PHP 5.3.3. The culprit seems to be the exportXML function: eliminating this function resolves the issue. Any suggestions? I&a ...

Guide on linking a textarea with a boolean value in the child component

I have created a form component consisting of two components. The first component looks like this: <template> <div class="flex flex-col items-center justify-center gap-2"> <div class="flex w-[80%] items-center justify-ce ...