Show and Hide Element In JavaScript By Class

HTML structure

In the HTML markup there is a button with the initial position “Show item” and a hidden text block. When you click on the button, the text block is shown. When the button is clicked again it is hidden. Set the content class, responsible for design, and the hidden class for the text block. From the name of the latter it is clear that this class hides content until the user clicks the button.

 <button class="btn" type="button">
    Show item
</button>
<div class="content hidden">

     <!-- Your element -->
</div> 

CSS code

Let’s paint our button with a linear gradient and set a light shadow.

 .btn{
    text-decoration: none;
    text-align: center;
    width: 250px;
    padding: 20px 0;
    border: solid 1px #004F72;
    border-radius: 4px;
    font: 20px Arial, Helvetica, sans-serif;
    font-weight: bold;
      color: #E5FFFF;
    background-color: #3BA4C7;
    background-image: linear-gradient(top, #3BA4C7 0% ,#1982A5 100%);
       box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
      outline: none;
}

.content {
    margin-top: 20px;
    padding: 20px;
    border: solid 1px rgb(214, 218, 219);
    border-radius: 4px;
    font-family: Calibri, 'Trebuchet MS', sans-serif;
}
   
.hidden {
    display: none; // hides text
}  

JavaScript code

When the button is clicked, the hidden class of the text block must be removed and then it won’t be hidden anymore. A second click on the button, on the contrary, hangs the hidden class on the content block, thereby hiding it. As you can see, the entire mechanism is tied to the hidden class.

Let’s create two variables to which we’ll assign the button and the block by selector names. Then we will catch the event of clicking on the button with addEventListener event handler. The first parameter we pass the click event, and the second parameter is the name of function btnClick, in which we describe the actions that must happen after clicking on the button. The first thing to do is to find the hidden class and use the toggle method to add the hidden class if it doesn’t exist and remove it if it does. In addition, the inscription “Show Item / Hide Item” should change on the button. To do this, we turn to the button’s textContent property and create an if-else condition. If the block with the content class also contains the hidden class, then change the inscription on the button to “Hide Item”. Otherwise leave it as “Show item”.

 const btn = document.querySelector(".btn");
const content = document.querySelector(".content");

btn.addEventListener("click", btnClick);

function btnClick() {
    console.log(content.classList);

    if (content.classList.contains("hidden")) {
        btn.textContent = "Hide Element";
    } else {
        btn.textContent = "Show Element";
    }

    content.classList.toggle("hidden");
}

Recommended Articles