How can I set the visibility of a specific div based on the state of a switch in the CMS using HTML embed in Webflow?

Published on
September 22, 2023

To set the visibility of a specific div based on the state of a switch in the CMS using HTML embed in Webflow, you can follow these steps:

  1. Begin by creating a switch field in your CMS collection. Go to your Webflow project dashboard, navigate to the "CMS Collections" tab, select your desired collection, and click on the "Add Field" button. Choose the "Switch" field type and give it a name.

  2. Create a unique identifier for the div that you want to show or hide. This can be done by adding a custom attribute to the div, such as data-id. Assign a unique value, like "div-1", to identify it later.

  3. Now, go to the page where you want to display the div based on the switch's state. Add an HTML embed component to the page by dragging it from the elements panel.

  4. Inside the HTML embed component, you can write custom code using JavaScript to handle the visibility of the div. Here's an example code snippet:

    ```html

    ```

  • In this code snippet, we create a function called showHideDiv() that will be called whenever the page loads to check the switch's state and show or hide the div accordingly.
  • The variable switchState retrieves the value of the switch field from the CMS. Make sure to replace 'collectionField.switchField' with the actual switch field name you set in your CMS collection.
  • The div variable retrieves the div using its custom attribute. Make sure to replace 'div-1' with the actual value you assigned to the div's custom attribute.
  • Depending on the switch's state (either true or false), we set the div's display style to either 'block' (visible) or 'none' (hidden).
  1. Save your changes and publish your Webflow project.

Now, when the switch field is turned on in the CMS, the specified div will be visible on the page. If the switch is turned off, the div will be hidden.

Note:

  • Make sure you replace 'collectionField.switchField' with the actual switch field name you set in your CMS collection, and 'div-1' with the actual value you assigned to the div's custom attribute.
  • Use this code template as a starting point and modify it as needed to suit your specific requirements.

Example Questions:

  1. How to set visibility of a specific div based on a switch in Webflow CMS?
  2. What is an HTML embed in Webflow and how can it be used for visibility control?
  3. Can I use JavaScript to handle conditional visibility of elements in Webflow?