When you want a button to display a random item from a Collection in Webflow without page loads, you can use custom JavaScript while ensuring that sensitive data is secure.
1. Prepare Initial Setup
- Create a Collection in Webflow containing the items you want to display.
- Add a Button on your Webflow page that will trigger the random item display.
2. Use CMS Collection List
- Bind a Collection List to the existing Collection on the page where you want items displayed.
- Hide all items using custom CSS (e.g., using
display: none;), so they don't show immediately.
3. Add Custom JavaScript
- Insert custom JavaScript within the before /body tag section of your page settings.
- Access and store items by iterating through the Collection List using JavaScript to randomly display one item handler.
4. Ensure Security
- Avoid using API keys directly in JavaScript. Since you’re not using Webflow CMS API for front-end, storing items via the collection list avoids this risk.
- Use Webflow’s built-in tools to dynamically manage data while keeping it secure from being accessed directly via the code.
5. JavaScript Code Example
- Select all items in the Collection list and hide them initially.
- On button click, use JavaScript to randomly select and display one of these hidden items.
Summary
You can indeed make a button display a random item from a Webflow Collection using custom JavaScript and CMS features. By not including any sensitive data in your JavaScript and managing items within the Webflow environment, you maintain both functionality and security.