Act as an ES5 web developer. I have a bar on the top of my webpage that tells users that a sale is running out in X amount of time. They can close the bar by hitting X. However, when they hit X, I want the bar to shrink before disappearing to prevent the jump that happens when I simply call .remove(). Output a CSS and JS solution. You may edit the #timerBanner element.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
function initTimerBanner() {
var banner = document.getElementById('timerBanner');
var closeButton = banner.querySelector('.close-btn'); // Adjust selector as needed
if (closeButton) {
closeButton.addEventListener('click', function() {
closeBanner();
});
}
function closeBanner() {
// Add the closing class to trigger the shrink animation
banner.classList.add('closing');
// Remove the element after the transition completes
setTimeout(function() {
if (banner.parentNode) {
banner.parentNode.removeChild(banner);
}
}, 300); // Match the transition duration (0.3s = 300ms)
}
}
// Initialize when the DOM is ready
document.addEventListener('DOMContentLoaded', function() {
initTimerBanner();
});
Alternative approach using transitionend event (more precise):
javascript
function initTimerBanner() {
var banner = document.getElementById('timerBanner');
var closeButton = banner.querySelector('.close-btn');
if (closeButton) {
closeButton.addEventListener('click', function() {
closeBanner();
});
}
function closeBanner() {
banner.classList.add('closing');
// Listen for the transition to complete
banner.addEventListener('transitionend', function handleTransitionEnd(e) {
// Make sure we're responding to the height transition, not others
if (e.propertyName === 'height') {
banner.removeEventListener('transitionend', handleTransitionEnd);
if (banner.parentNode) {
banner.parentNode.removeChild(banner);
}
}
});
}
}
document.addEventListener('DOMContentLoaded', function() {
initTimerBanner();
});
Key points:
The CSS transition animates height, padding, and margin properties
The .closing class reduces height to 0 and vertical padding to 0 (keeping horizontal padding to maintain content positioning during animation)
overflow: hidden ensures content doesn't spill out during the shrinking animation
The JavaScript waits for the animation to complete before removing the element from the DOM
Using transitionend event is more precise than setTimeout, but setTimeout is simpler and works reliably
The animation duration is set to 0.3 seconds, but you can adjust this in both the CSS transition and the JavaScript timeout to match your preference.