I’ve got a CMS collection, “Projects”, that has two color inputs. I’m using them as “Gradient 1” and “Gradient 2”, then connecting them to different parts of my page design as well as calling on them in some custom code elements.
So far, It’s worked on the individual “Project” page template, but not on a separate page with a CMS collection (ie. a “Projects” or “Blog” aggregate page). The code embed seems to pull the Gradient colors from the last CMS item and changes the color on all the previous cards/elements.
I’d like to have each card’s tag changed to match the “Gradient” colors of the associated project.
I was able to get the code to work like you showed, but wasn’t able to target other elements in my Collection Item. ie. the code and setup worked to change the background of the entire Collection Item, but I can’t seem to get it to change an element within the card, like the tag background or another div block.
With a need to publish the site, I connected many properties to the CMS background color (settings>get Background Color>gradient 1), but not any actual gradients.
If you’d like to help more, I’d be appreciative, but have a non-ideal solution that works for now.
hi @Kaleb_Dean the code I have provided was only example how it can be done. If you would like to use it on ANY element inside card just chin your selector means instead of selecting “.item-element” use what ever elemenet you need to target.
Here is slightly improved code. I have also add some comments to be clear what code does when is executed.
// COLORS
// get all collection Items on page in an Array
const collectionItems = [...document.querySelectorAll(".event-item")];
// loop over Array and for each Item in Array do ...
collectionItems.forEach((item) => {
// ... get any element inside Item
const myElementOneInsideOfItem = item.querySelector(".date")
// you can chose as many elements you need
// OPTION: const myElementTwoInsideOfItem = item.querySelector(".subtitle")
//... store value of colors in variables from text field in collection _(as explained before)_
const c1 = item.querySelector(".c-1").innerText;
const c2 = item.querySelector(".c-2").innerText;
// ... finally add gradient where colors are defined from catecory to chosen element
myElementOneInsideOfItem.style.background = `linear-gradient(135deg, ${c1} 0%, ${c2} 100%)`
// OPTION: myElementTwoInsideOfItem.style.background = `linear-gradient(135deg, ${c1} 0%, ${c2} 100%)
});
If you will have many elements you would like to add this gradiend, can also create an Array from myElementInsideOfItem_1, myElementInsideOfItem_2 .. myElementInsideOfItem_50 and create another loop to add gradient to each inner item dynamically.
Thanks for taking the time to make the video and do a couple versions of code for me! I have an idea of HTML and CSS, but never touch any kind of scripting, so thank you. This worked great!
I’ll post a demo video, too, for anyone who’s looking to do this in the future.