How to programmatically add a class to an element in Bricks

This Pro tutorial shows how a dynamic class can be added to a query loop element in Bricks programmatically.

Let's take an example where posts of Events CPT are being shown using a query loop.

The objective is to add a class of future-event for all upcoming events that occur in the future and past-event for events that happened in the past to the element on which query loop is enabled. We can then add custom CSS to make it easy for the visitors to distinguish between past and future events.

Instead of adding a class dynamically by checking the value of the event-date custom field for each post, we could use the attributes feature and add an attribute called say, data-status and set its value to a dynamic function that returns the appropriate string (future-event or past-event). Then add the custom CSS using the [data-status="future-event"] and [data-status="past-event"] selectors.

The above approach is fine for most use cases but for whatever reason if you wish to set the date status strings as a class, your first instinct would be to use the attributes feature and add a class attribute with the value = a custom dynamic function. A potential problem with this is that the existing classes will be replaced with the class value set in the attribute.

Below is the sample code to add a hard-coded static class to each item in the loop. We will then modify it to make it dynamic.

static class
dynamic class

This is a BricksLabs Pro tutorial.

For full access login below or create your BricksLabs Pro account

Get access to all 525 Bricks code tutorials with BricksLabs Pro

Related Tutorials..

Pro
Restrict Content Pro in Bricks

Restrict Content Pro in Bricks

This Pro tutorial provides the steps to restrict Pages and individual elements like Sections in Bricks depending on whether the current user has any active…
Filtering Breadcrumbs in Bricks

Filtering Breadcrumbs in Bricks

Using the bricks/breadcrumbs/items filter to modify Bricks' breadcrumbs’ element programmatically.
Categories:
Show Product Categories Count Using Bricks Filter Hook

Show Product Categories Count Using Bricks Filter Hook

Unable to find terms count from the Dynamic Data provided by Bricks theme? It's okay, this simple tutorial shows you how to properly get the…
Categories:
Tags: