Is it possible to make a button on a Webflow page display a random item from a Collection without any page loads using custom Javascript and without exposing sensitive data or API keys to users?

TL;DR
  • Set up a Webflow Collection, add a button to trigger item display, and bind a Collection List to the page.
  • Use custom CSS to hide items and insert JavaScript to access and randomly display an item from the Collection List.
  • Ensure security by not using API keys in JavaScript and leveraging Webflow's built-in tools for safe data handling.

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.

Rate this answer

Other Webflow Questions