PIKADEMIA

Projekt edukacji alternatywnej

Wyświetlanie i ukrywanie zawartości po kliknięciu – accordion

Wyświetlanie i ukrywanie div o klasie toggleMsg po kliknięciu na inny obiekt poprzez dodawanie i usuwanie klasy

<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="row tg">
            <div class="col-md-6 toggleClick">Click to show the message 1</div>
            <div class="col-md-6 toggleMsg d-none">The message 1</div>
        </div>
        <div class="row tg">
            <div class="col-md-6 toggleClick">Click to show the message 1</div>
            <div class="col-md-6 toggleMsg d-none">The message 2</div>
        </div>
    </div>
    <script type="text/javascript" src="main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
</body>
</html>
.tg div:first-child{
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #44aaaa;
}
.tg div:last-child{
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #584dee;
}
let toggleItems = document.getElementsByClassName("toggleClick");
for(let i=0;i<toggleItems.length;i++){
    toggleItems[i].addEventListener("click", openHide);
}

function openHide(){
    let msg = this.parentNode.getElementsByClassName("toggleMsg")[0];
    if(msg.classList.contains("d-none")){
        msg.classList.remove("d-none");
        this.textContent = "Click to hide";
    }else{
        msg.classList += " d-none";
        this.textContent = "Click to show the message";
    }
}