Add Additional Classes Based on Dynamic Data to Elements

It would great if CSS classes can be added to an element from a dynamic data field.

Even better if we could include conditions on it.

For example I have a card in a query loop using data from a Custom Post Type built with Metabox.

For some items I want the card to be featured. To do this all I need to do is add a class to the card.

It would be nice if I could create one card and on it add a condition that says if this dynamic data field equals true (ie it is a Featured Card) then add this class ā€œfeatured-cardā€.

I know there are ways around this like created 2 cards but that is very inefficient since these cards are pricing cards and contain a lot of elements with the only difference being 1 class. I could also do this with a code block by adding the cards code to the block and then pulling the class with PHP like so ā€œ<?php the_field('custom-class-field-name'); ?>ā€ but once again it’s not ideal.

I also did try doing this using attributes and setting the name to ā€œclassā€ but that is not conditional and it also replaces the entire class list and does not append the custom class to the end of the list. (and actually in some cases using ā€œclassā€ as the name of the attribute causes Bricks to crash when previewing on the front end)

5 Likes

Dynamic classes would be a good idea, but for now a solution to your issue…

  • Create a custom function that returns ā€˜featured’ or ā€˜regular’ based on your condition.
  • Add in a new data attribute to get that value. data-card-type
  • Use the ā€˜echo’ dynamic tag to populate the attribute’s value based on what the function is returning.
  • Style the featured card using the ā€˜[data-card-type=featured]’ as the selector instead of a class.

eg css…

/* regular card styles */
.card {

}

/* featured card styles */
.card[data-card-type=featured] {

}
6 Likes

Yup that is what I am doing for now.

There is a beautiful tutorial by Kevin Geary: DYNAMICALLY Control Template Behavior in Oxygen With Custom Data Attributes! - YouTube
You can apply the same technique in Bricks for exactly what you were asking above…

1 Like

I don’t understand why it isn’t a thing yet.

The solution with attributes does replace the previous inserted class as you mentioned, but it is possible to move all the classes to the attribute field. Yet:

  • Does not solves the condition as you intended.
  • Not intuitive for future maintenance
  • You cannot see the css applyed on the admin