Hey Webflow community!
We wanted to share some snippets that we’ve found to be useful in our client work. Today, we’re excited to share a piece of code that allows you to insert static elements into CMS Collection Lists at a specific position.
What does this code do?
This script allows you to insert a static element (like an advertisement or a featured item) into a CMS Collection List at a specified position. If the list doesn’t have enough items to insert at the specified position, the static element is appended to the end of the list.
While there is a solution by finsweet
How to use the code:
- Create your CMS Collection List in Webflow.
- Create a static element that you want to insert into the list. This could be a div with your ad content, a featured item, or any other HTML element.
- Give your static element a unique ID (e.g., ‘staticItemID’). (Your static items has to be placed on the same page.)
- Give your Collection List a unique ID (e.g., ‘collectionListId’).
- Add the following code to your page’s custom code section:
<script>
Webflow.push(function() {
const staticItem = document.getElementById('staticItemID'); // Adjust ID to the one you have in Webflow
const collectionList = document.getElementById('collectionListId'); //Adjust ID to the one you have in Webflow
const placementPosition = 2; // Adjust this value to change the insertion position
if (staticItem && collectionList) {
const items = collectionList.children;
if (items.length >= placementPosition) {
collectionList.insertBefore(staticItem, items[placementPosition]);
} else {
collectionList.appendChild(staticItem);
}
}
});
</script>
- Adjust the
placementPosition
variable to control where the static element is inserted. For example, setting it to 2 will insert the element after the second item in the list.
How it works:
- The script waits for Webflow to finish loading.
- It finds the static element and the collection list using their IDs.
- It checks if both elements exist.
- If the collection list has enough items, it inserts the static element at the specified position.
- If the list doesn’t have enough items, it appends the static element to the end.
This snippet is particularly useful for inserting ads, featured content, or any other static elements into dynamic lists without affecting the CMS structure.
Example:
Note: We’re aware that Finsweet offers a solution called “Static to Collection List” (Static to Collection List) that provides similar functionality. However, we understand that some developers prefer to use a small, customizable code snippet instead of relying on a third-party solution. This snippet is for those who prefer that approach.
We hope you find this helpful! Feel free to ask any questions or share your experiences using this snippet.