Webflow sync, pageviews & more.
NEW

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
  • Pre-render all CMS Collection items on the page inside a hidden container (display: none) so JavaScript can access them without API calls.
  • Use a button with a JavaScript click listener that randomly selects one hidden CMS item, extracts its content, and displays it in a visible placeholder element.

You can make a Webflow button display a random CMS Collection item without page reload using custom JavaScript, but it depends on how secure and performant you want it to be.

Here’s how to do it without exposing sensitive data or API keys and without causing a page load:


1. Use Webflow CMS Collections Rendered on Page with display: none

  • Place all CMS items on the page, such as in a Collection List, but visually hide them using display: none or using a hidden container.
  • Since the items are already in the DOM, JavaScript can randomly select one client-side without API calls or security issues.
  • You avoid exposing API keys, since no client-side API requests are made.

2. Style the Collection List for Hidden Access

  • Wrap your CMS Collection List in a div with display: none or use visibility classes to hide it without removing it from the DOM.
  • Make sure each item’s relevant content (title, image, link, etc.) is still rendered within the HTML.

3. Add a Button with Custom JavaScript Listener

  • Add a Webflow Button element, give it an ID like #randomButton.
  • Add a visible placeholder element (e.g., a div or modal) where the random item will be displayed (e.g., #randomDisplay).

4. Write JavaScript to Randomly Pick and Display an Item

  • Add a custom script in the page’s Footer Custom Code or using an Embed element.
  • The script should:
  • Select all hidden CMS items,
  • Randomly pick one (Math.random()),
  • Extract its inner content,
  • Copy and display it inside the placeholder element.

Example logic:

  • Grab all elements with .cms-item
  • Randomly select one
  • Clone its contents and append to #randomDisplay

5. Security Notes

  • Since you're not using the Webflow CMS API or exposing external services, there is no risk of leaking sensitive data.
  • The only limitation is that all CMS items must exist in the DOM already. If you have a large Collection, it may affect page performance.

Summary

Yes, you can display a random CMS item on a button click using custom JavaScript with pre-rendered, hidden CMS Collection items. This requires no page reload, no API usage, and keeps all sensitive data protected by not exposing any API keys.

Rate this answer

Other Webflow Questions