50% discount on BricksLabs Pro Membership Lifetime Access. Use coupon: GOBRICKS

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 Pro members-only tutorial.

To get full access, login below or sign up for a Pro Account

Leave your comment