I have added a custom code to set a random background image to a div. This code works but only on the first page of the collection since Im using pagination attributes. How can I fix this?
@stevenjhilario you can use the Attributes API for this, here is an example:
<script>
window.fsAttributes = window.fsAttributes || [];
window.fsAttributes.push([
'cmsload',
(listInstances) => {
console.log('cmsload Successfully loaded!');
// The callback passes a `listInstances` array with all the `CMSList` instances on the page.
const [listInstance] = listInstances;
// The `renderitems` event runs whenever the list renders items after switching pages.
listInstance.on('renderitems', (renderedItems) => {
console.log(renderedItems);
// Add code that will run each time new items are rendered on the page
});
},
]);
</script>
For your particular case, you can replace the code on your page with this:
<script>
const backgroundImages = [
'https://assets.website-files.com/642f06aad4855fdea1778af3/645d0788655937ed1ecbca1e_Rotating%20Blog%20Cover%20-%206.webp',
'https://assets.website-files.com/642f06aad4855fdea1778af3/645d0788f8f2b42feafdcf77_Rotating%20Blog%20Cover%20-%202.webp',
'https://assets.website-files.com/642f06aad4855fdea1778af3/645d078875de33d4455ac0e7_Rotating%20Blog%20Cover%20-%205.webp',
'https://assets.website-files.com/642f06aad4855fdea1778af3/645d0788678fda17deb31d05_Rotating%20Blog%20Cover%20-%2010.webp',
'https://assets.website-files.com/642f06aad4855fdea1778af3/645d0788862633c197de77ba_Rotating%20Blog%20Cover%20-%204.webp',
// Add more image URLs or filenames as needed
];
function applyRandomBackground() {
const randomBackgrounds = document.querySelectorAll('.random-background');
randomBackgrounds.forEach((randomBackground) => {
const randomIndex = Math.floor(Math.random() * backgroundImages.length);
const randomImage = backgroundImages[randomIndex];
randomBackground.style.backgroundImage = `url('${randomImage}')`;
});
}
window.fsAttributes = window.fsAttributes || [];
window.fsAttributes.push([
'cmsload',
(listInstances) => {
// Apply random background when the page loads initially
applyRandomBackground();
// The callback passes a `listInstances` array with all the `CMSList` instances on the page.
const [listInstance] = listInstances;
// The `renderitems` event runs whenever the list renders items after switching pages.
listInstance.on('renderitems', (renderedItems) => {
// Apply random background when new items are rendered
applyRandomBackground();
});
},
]);
</script>
Thank you! this worked!