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 full access to all 220+ Bricks tutorials with BricksLabs Pro

2 comments

Leave your comment