Session-Based Webflow Information Banner Cloneable
The Smart Banner: Show Every Session, Hide on Demand (No Cookies Needed)
Why This Works Great for Webflow
- No classes needed ✅ (only uses banner-element attributes)
- Session-based storage ✅ (hides per session without cookies)
- Prevents flashing issues ✅ (banner visibility controlled smoothly)
- Fully Webflow-friendly ✅ (works with Webflow’s native structure)
Full Post on Milk Moon Studio's Blog
1<!-- 🎯 Session-Based Banner Script (No Cookies, Attributes Only) -->
2<script>
3document.addEventListener('DOMContentLoaded', function () {
4 /**
5 * Function to initialize the session-based banner behavior.
6 * - Shows the banner on every new session but allows users to hide it.
7 * - Uses `sessionStorage` (not cookies) to track if the user closed the banner.
8 * - Fully attribute-based for Webflow compatibility.
9 */
10 function initializeBanner() {
11 const banner = document.querySelector('[banner-element="banner-component"]'); // Banner container
12 const closeButton = document.querySelector('[banner-element="close"]'); // Close button
13
14 // Ensure both elements exist before proceeding
15 if (!banner || !closeButton) {
16 return;
17 }
18
19 // Step 1: Make the banner visible (prevents flashing issues)
20 banner.style.visibility = 'visible';
21
22 // Step 2: Check if the banner was closed this session
23 if (!sessionStorage.getItem('banner-closed')) {
24 banner.style.opacity = '1'; // Smooth fade-in effect
25 } else {
26 banner.style.display = 'none'; // Hide if previously closed
27 }
28
29 // Step 3: Close button event listener
30 closeButton.addEventListener('click', function () {
31 banner.style.opacity = '0'; // Start fade-out transition
32
33 // Wait for transition to complete before fully hiding the banner
34 setTimeout(() => {
35 banner.style.display = 'none';
36 }, 300); // Matches CSS transition time
37
38 // Store the closed state in sessionStorage (resets each session)
39 sessionStorage.setItem('banner-closed', 'true');
40 });
41 }
42
43 /**
44 * MutationObserver: Ensures the script runs only when Webflow has rendered elements.
45 * - Listens for dynamically loaded content to prevent errors.
46 * - Runs `initializeBanner()` once all required elements exist.
47 */
48 const observer = new MutationObserver((mutations, obs) => {
49 if (
50 document.querySelector('[banner-element="banner-component"]') &&
51 document.querySelector('[banner-element="close"]')
52 ) {
53 initializeBanner(); // Initialize banner once elements are ready
54 obs.disconnect(); // Stop observing after successful initialization
55 }
56 });
57
58 // Observe the document for dynamically added elements
59 observer.observe(document.body, { childList: true, subtree: true });
60});
61</script>