10th Aug '22
/
8 comments

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 610 Bricks code tutorials with BricksLabs Pro

Related Tutorials..

Pro
Making a Nav Menu Item Active for Custom Post Type Single Views in WordPress

Making a Nav Menu Item Active for Custom Post Type Single Views in WordPress

Consider this scenario: CPT: project Page titled "Project" is being used to show a list/grid of all the projects rather than the CPT archive. When…
Categories:
How to Add a Custom Control Field to an Element in Bricks

How to Add a Custom Control Field to an Element in Bricks

In this tutorial, we'll learn how to add a custom control field to an element and dynamically change a CSS property inside the builder. Introduction…
Categories:
Tags:
Pro
ACF Relationship Select Filter in Bricks

ACF Relationship Select Filter in Bricks

In the BricksLabs Facebook group, a user asks: I'm learning about ACF relationships and attempting to output a list of posts on any given page,…
Categories:
Pro
Limit the Number of Posts in a Bricks Query Loop of Relationship Type

Limit the Number of Posts in a Bricks Query Loop of Relationship Type

Updated on 12 Dec 2023 Bricks Query Loop popup does not have a control for setting the number of posts to be output when the…