Sure! Here's a complete solution using pure CSS and JavaScript (ES5) to create a smooth shrinking animation before removing the banner when the user clicks the close button.
✅ Goal:
- Show a top bar with a countdown message.
- User can click an "X" to close it.
- When closed, the bar should shrink smoothly instead of disappearing abruptly.
- Prevents page content from jumping when the element is removed.
💡 HTML
Make sure your HTML includes the #timerBanner with a close button:
<div id="timerBanner">
<span>Hurry! Sale ends in X hours!</span>
<button id="closeBanner">×</button>
</div>
🎨 CSS (ES5 Compatible)
Use transitions to animate height and opacity:
#timerBanner {
background-color: #ffdd57;
color: #333;
text-align: center;
padding: 10px 20px;
position: relative;
transition: all 0.4s ease-out;
overflow: hidden;
height: auto;
max-height: 100px;
}
#timerBanner.collapsing {
opacity: 0;
max-height: 0;
padding: 0;
height: 0;
}
⚙️ JavaScript (ES5)
Add an event listener to handle the closing animation:
document.getElementById('closeBanner').onclick = function () {
var banner = document.getElementById('timerBanner');
// Start the collapse animation
banner.classList.add('collapsing');
// Wait for the transition to finish before removing the element
banner.addEventListener('transitionend', function onTransitionEnd() {
banner.removeEventListener('transitionend', onTransitionEnd);
if (banner.parentNode) {
banner.parentNode.removeChild(banner);
}
});
};
✅ How It Works:
- Clicking the "X" adds the
.collapsing class.
- The class animates the height and opacity to zero.
- Once the animation completes (
transitionend), the element is safely removed.
- This prevents layout jump because the banner shrinks smoothly first.
Let me know if you want to store this state in cookies/localStorage so users don’t see it again until next visit!