I’m trying to embed a Date-Field (“Custom Date and Time”) in a Collection list with the Embed Component, add 14 Days to that date and then use the current date to only show a certain div (green block with id=current) if it falls in the 14 day window and if not will be hidden.
From the console.log I can tell that the code is working correctly, but for some reason this is only affecting the first item in the collection and not the rest. Does anyone have a solution or workaround for this?
Thanks a ton for taking the time to help.
<script>
document.addEventListener("DOMContentLoaded", function() {
var current = new Date('Custom Date and Time CMS Date Field');
var weeks = new Date(current);
weeks.setDate(weeks.getDate()- 14);
weeks.setMonth(weeks.getMonth());
weeks.setYear(weeks.getYear());
if (current.getDate() > weeks.getDate()) {
document.getElementById('current').style.display = 'none';
}else {
document.getElementById('current').style.display = 'block';
}
console.log(current);
console.log(weeks);
});
</script>
I think that code assumes that you are using a single instance of an element with an ID of “current”.
The collection list will create the html with all items having the same id of “current” for the div with the current-class assigned. When the custom code runs, it only runs for the first item.
To get around this, you can adjust the current-class to be above the custom code, so that the div is created before the code runs:
Then you can adjust the embed code to change the name of the div with id “current” to a new id of “current_SLUG” where SLUG is the dynamic slug of the item in the collection list.
This gives each item a dynamic ID. Next I would update your code embed with the SLUG to show or hide the current-class div based on the dynamic ID:
Dave! Thanks so much for the quick reply and tips… and I’m also SUPER grateful for the loads of other feedback and help you’ve provided on the forum, thank you.
It didn’t even cross my mind to use the SLUG to drive the Id’s. This worked exactly as I wanted it after moving the DOM to the top. I still need to adjust the script slightly as it is currently only looking at the date of the month(number) and disregarding the actual Month & Year.
I’ll be sure to post the script here for the community once I’ve got it working 100%.
Your help is much appreciated, thanks again sensei.
Yeah thanks but for me it’s working with the embed above.
But i have a bigger problem, when i add the finsweet attribute load more library it works but only for the first item like before.