Skip to content
Advertisements

JavaScript Box Puzzle Animation

CODEPEN

JavaScript Box Puzzle Animation

HTML CODE:

    <ul class="parent">
        <li class="left"></li>
        <li class="right"></li>
        <li class="left"></li>
        <li class="right"></li>
        <li class="left"></li>
        <li class="right"></li>
        <li class="left"></li>
        <li class="right"></li>
    </ul>

CSS CODE:

body {
    margin: 0;
    padding: 0;
    background: #333;
}
ul{
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    list-style-type: none;
    flex-direction: column;
    height: 100vh;
}
.left {
    margin: 5px;
    width: 100px;
    height: 30px;
    background: #d44118;
    transition: all .4s ease;
    border: 2px solid transparent;
    border-radius: 10px;
}
.lef {
    background: #b73131;
    border: 2px solid #262626;
    transform: translateX(40px);
    transition: all .4s ease;
}
.right {
    margin: 5px;
    width: 100px;
    height: 30px;
    background: #d44118;
    transition: all .4s ease;
    border: 2px solid transparent;
    border-radius: 10px;
}
.rig {
    background: #e0cd1c;
    border: 2px solid #262626;
    transform: translateX(-40px);
    transition: all .4s ease;
}

JS CODE:

   let ul = document.querySelector(".parent");

        ul.addEventListener("click", (e) => {
            if (e.target.matches("li")) {
                e.target.classList.toggle("lef");
            } else {
                Array.from(document.querySelectorAll(".left")).forEach((item) =>
                    item.classList.remove("lef"));
            }
        });

        ul.addEventListener("click", (e) => {
            if (e.target.matches("li")) {
                e.target.classList.toggle("rig");
            } else {
                Array.from(document.querySelectorAll(".right")).forEach((item) =>
                    item.classList.remove("rig"));
            }
        });
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: