Sử dụng GSAP Timeline để animate show/hide search box khi click button (ok)
✅ 1. HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>GSAP Timeline Show Search Box</title>
<style>
body {
font-family: sans-serif;
background: #f0f0f0;
padding: 50px;
}
.search-btn {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
}
.search-box {
width: 300px;
padding: 20px;
background: white;
border: 1px solid #ccc;
margin-top: 20px;
opacity: 0;
transform: translateY(-20px);
display: none; /* hidden by default */
}
</style>
</head>
<body>
<button class="search-btn">Search</button>
<div class="search-box">
<input type="text" placeholder="Search..." style="width: 100%; padding: 10px;">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script>
const btn = document.querySelector(".search-btn");
const box = document.querySelector(".search-box");
// Create timeline paused
const tl = gsap.timeline({ paused: true, reversed: true });
tl.to(box, {
display: "block", // instantly set display block
duration: 0,
})
.fromTo(box,
{
opacity: 0,
y: -20
},
{
opacity: 1,
y: 0,
duration: 0.5,
ease: "power2.out"
}
);
btn.addEventListener("click", () => {
if (tl.reversed()) {
tl.play();
} else {
tl.reverse();
}
});
// Optional: hide box completely after reverse animation ends
tl.eventCallback("onReverseComplete", () => {
box.style.display = "none";
});
</script>
</body>
</html>
PreviousSử dụng ScrollSmoother thay thế Locomotive Scroll hay Lenis. (ok)NextĐặt chiều cao bằng nhau, Set equal height, same height (ok)
Last updated
Was this helpful?