Conditional visibility is a versatile tool in web development. It allows you to set rules or logic that determine whether certain elements on a website should be visible or hidden based on specific conditions or criteria. These conditions can be user actions, data inputs, or other contextual factors. Using conditional visibility, you can adapt your website to various user interactions and contexts.

For example:-

User Actions

Showing a detailed view of a product only when a user clicks on a "More Info" button.

User Status

Displaying different content based on whether a user is logged in or logged out.

Data-Driven Conditions

Hiding certain form fields unless a specific checkbox is selected.

Field Values

We display additional content or options if a specific field is set or meets certain criteria. For example, we show additional shipping options if a "country" field has a particular value.

Device Type

Displaying different content for mobile users compared to desktop users.

How Conditional Visibility Works

The methods of conditional visibility also tend to fall into the following modes: -

JavaScript and CSS: Often, JavaScript is used in conjunction with CSS to change the visibility of elements based on conditions dynamically.

Frameworks and Libraries: Many modern web development frameworks (like React, Angular, and Vue.js) provide built-in support for conditional rendering.

Backend Logic: Sometimes, server-side logic decides what content to send to the client based on the user's request.

Examples of Conditional Visibility

  1. A website might show a pop-up modal only if the user has yet to visit the site before.
  2. An e-commerce site could display a discount banner to users with items in their cart that still need to be checked out.
  3. A form might reveal additional fields when users select a particular option from a dropdown menu.
  4. Displaying a message or additional fields when a specific form field contains a particular value, such as showing a text box for further comments if the user selects "Other" from a list of reasons for contacting support.

Conditional Visibility in Website Builders

Familiarity with conditional visibility is essential for anyone working with modern web development and web builders, as it plays a crucial role in creating dynamic, user-friendly websites. Conditional visibility is the ability to programmatically show or hide elements on a web page based on specific conditions or criteria, such as user interactions, data inputs, or contextual factors.

In web builders like Webflow and Framer, conditional visibility is a ubiquitous feature that allows designers and developers to create more personalised and responsive web experiences without extensive coding. These platforms provide intuitive interfaces and powerful tools to implement conditional visibility rules quickly.

Conditional Visibility in Webflow

Webflow is a popular no-code web design tool that empowers users to design, build, and launch responsive websites visually. Conditional visibility in Webflow is straightforward and highly versatile:

  1. User Interface: Webflow's interface allows users to set visibility conditions directly within the design view. Users can specify when elements should be shown or hidden based on various triggers, such as form inputs, user authentication status, or custom conditions.
  2. Dynamic Data: Webflow CMS (Content Management System) leverages conditional visibility to display dynamic content based on collection fields. For instance, a blog post template might only show an "Author Bio" section if the author bio text field is populated.
  3. Interactions and Animations: Webflow's interactions feature can trigger visibility changes, such as displaying a modal when a button is clicked or hiding a section when a user scrolls past a certain point.

Conditional Visibility in Framer

Framer is another powerful tool for designing interactive prototypes and fully functional websites. It combines design and development in a seamless workflow, making conditional visibility an integral part of the user experience:

  1. Component-Based Design: Framer allows users to create reusable components with conditional visibility rules. For example, a navigation bar component might change its visibility based on the user's scroll position or screen size.
  2. Logic and State Management: Framer supports logic and state management, enabling more complex conditional visibility scenarios. Users can define states and transitions, showing or hiding elements based on user interactions or data changes.
  3. Visual Coding: Framer's visual coding environment lets users define conditional visibility rules using a combination of drag-and-drop elements and code, providing flexibility for designers and developers.

Ubiquity and Benefits of Conditional Visibility in Website Builders

The ubiquity of conditional visibility in website builders like Webflow and Framer highlights its importance in modern web design and development. The benefits include:

  • Improved User Experience: Websites can provide a more tailored and engaging experience by showing relevant content based on user actions and context.
  • Enhanced Performance: Conditional visibility can improve performance by only loading and displaying necessary content, reducing page load times and resource usage.
  • Design Flexibility: Web builders with robust conditional visibility features allow for greater creativity and flexibility in designing interactive and dynamic web pages.

In summary, conditional visibility is a fundamental feature in web builders like Webflow and Framer. It enables easy creation of sophisticated, responsive, and user-centric websites. Familiarity with this concept is crucial for maximising the potential of these tools and delivering high-quality web experiences.

Conditional Visibility with CSS and Data Attributes

We have looked at the most common methods of Conditional Visibility. Still, a lesser-known but surprisingly effective method of creating conditional visibility on elements uses CSS and data attributes. This approach also fills limitations found in website builders such as Webflow, where conditional visibility is confined to particular variables or limited by and/or combinations. For example, in Webflow, you can sometimes only create a single conditional visibility rule such as "if x element is set". However, you may wish to extend this if a particular field in the CMS has content or contains specific text or string. As attributes extend across uses and platforms and CMS functionality, achieving conditional visibility in this way makes a lot of sense.

Examples of Conditional Visibility with CSS and Data Attributes

You can use CSS attribute selectors to apply styles based on the presence and value of data attributes. For example, you can style elements differently based on whether a data-visibility attribute (you can define it as per your needs) contains any value or is empty.

HTML

<div id="content" data-visibility="something"> <!-- Content here --> </div>

CSS

[data-visibility]:not([data-visibility=""]) { /* CSS rules here */}

This selector targets any element with a data-visibility attribute whose value is not an empty string, which is hard-coded or populated dynamically from a CMS. Here's a breakdown:

  • [data-visibility]: Selects elements that have the data-visibility attribute.
  • :not([data-visibility=""]): Filters out elements where the data-visibility attribute is equal to an empty string.

Here's how you might use it in your code:

HTML

<div id="content" data-visibility="something"> <!-- Content here --> </div>

CSS

/* Styles for elements where data-visibility has any non-empty value */
[data-visibility]:not([data-visibility=""]) {    
background-color: yellow; /* Example style */    
color: black; /* Example style */
}

/* Styles for elements where data-visibility is empty */
[data-visibility=""] {    
background-color: gray; /* Example style */    
color: white; /* Example style */
}

Or, at the base conditional visibility level, hide the div if the attribute doesn't have a value/string and is therefore empty: -

CSS

/* Hide the div by default */ 
#content { 
display: none; 
}
[data-visibility]:not([data-visibility=""]) {  
display: block!important;
}

Use Data Attributes to show a div based on one of two attributes conditionally.

We could extend the use of data attributes to hide or show a div based on whether one of two data attributes say 'data-hero-image' or 'data-hero-video' contains content:-

/* Hide the div by default */
#content {  
display: none;
}
/* Show the div if there's an image */
#content[data-image]:not([data-image=""]) {  
display: block;
}
/* Show the div if there's a video */
#content[data-video]:not([data-video=""]) {  
display: block;
}

How it Works

  • If the data-image attribute on the #content div is not an empty string, the #content div is displayed.
  • Similarly, the div is displayed if the data-video attribute on the #content div is not an empty string.
  • If both attributes are empty, the #content div remains hidden.

You can mix and match data attributes and CSS to create a more complex toggling of visibility and styles within parent-child hierarchies.

CSS Data Attributes Conditionals use the same logic as standard Webflow Conditional Visibility and other Website Builders when hiding content.

This conditional visibility functionality with CSS data attributes uses the same format as Webflow and other Website Builders, as native Conditions set the element to CSS display: none. In Webflow, this is achieved explicitly by adding the w-condition-invisible class, which adds the following CSS to hide an element: -

CSS

.w-dyn-hide, .w-dyn-bind-empty, .w-condition-invisible {
display: none !important;
}

Using display: none is a potential limitation of both approaches, as this only hides the elements visually in the browser, which is only relevant if you want to toggle the content. The code still resides in the website source, which adds to the page size and load. We could use JavaScript to remove the hidden content to reduce page bloat, and if you are interested, here is a way to achieve that.

Completely remove elements hidden by the Conditional Visibility Class with the Webflow Conditional Class as a default.

If you want to specify a specific class for removal, you can use this data-remove-condition data attribute and the following custom JavaScript. Set the data-remove-condition attribute on the element or parent of the element you want to remove; its value would be the class name you want to target for removal.

HTML

<div data-remove-condition="your-custom-class"><!-- Content inside --></div>

JavaScript

// Remove Visibility Class Condition with Data Attribute with Webflow a default  
    document.addEventListener("DOMContentLoaded", function() {
        var containers = document.querySelectorAll('[data-remove-condition]');

        containers.forEach(function(container) {
            var condition = container.getAttribute('data-remove-condition');
            var elementsToRemove;

            if (condition === 'invisible') {
                elementsToRemove = container.querySelectorAll('.w-condition-invisible');
            } else {
                // Include the dot before the class name
                elementsToRemove = container.querySelectorAll('.' + condition);
            }

            elementsToRemove.forEach(function(element) {
                element.parentNode.removeChild(element);
            });
        });
    });

Please leave any comments about Conditional Visibility and these alternate Data Attributes approaches in the comments section below.