How to Create Bootstrap Collapse with HTML CSS Javascript 

In this beginner level tutorial, we will create collapse similar to Bootstrap collapse.

We will learn to toggle multiple targets with HTML, CSS and Javascript.

Skills learned

  • DOM querySelector()
  • Toggle class with Javascript
  • Basic Flexbox

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bootstrap Collapse</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <div class="container">
        <button id="btn-1">Toggle First Element</button>
        <button id="btn-2">Toggle Second Element</button>
        <button id="btn-both">Toggle Both Element</button>
        <div class="toggle-content">
            <div class="content">
                <div class="content content-1">
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                        Harum, repellat tempora totam sed doloremque dolorem veniam
                        Aut natus, et labore, id quidem, animi maxime consequatur rem
                    </p>
                </div>
            </div>
            <div class="content">
                <div class="content content-2">
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                        Harum, repellat tempora totam sed doloremque dolorem veniam
                        Aut natus, et labore, id quidem, animi maxime consequatur rem
                    </p>
                </div>
            </div>
        </div>
    </div>
    <script src="index.js"></script>
</body>
</html>

CSS

body{
    box-sizing: border-box;
}
.container{
    width: 800px;
    margin: 150px auto;
    padding: 20px;
    border-radius: 15px;
    border: 3px solid #ccc;
}
button{
   padding: 15px;
   color: #fff;
   font-size: 1.2rem;
   border-radius: 5px;
   background: #007bff;
   border: none;
   cursor: pointer;
}
.toggle-content{
    display: flex;
    justify-content: space-around;
}
.content{
    padding: 15px;
    font-size: 1.2rem;
}
.content-1{
    border: 1px solid #ccc;
    visibility: hidden;
}
.content-2{
    border: 1px solid #ccc;
    visibility: hidden;
}
.display-text{
    visibility: visible;
}

Javascript

const btn_1 = document.querySelector("#btn-1");
const btn_2 = document.querySelector("#btn-2");
const btn_both = document.querySelector("#btn-both");

const content_1 = document.querySelector(".content-1");
const content_2 = document.querySelector(".content-2");

btn_1.addEventListener('click', function(e){
    content_1.classList.toggle('display-text');
})
btn_2.addEventListener('click', function(e){
    content_2.classList.toggle('display-text');
})
btn_both.addEventListener('click', function(e){
    content_1.classList.toggle('display-text');
    content_2.classList.toggle('display-text');
})