How to render random page image on reload?

I am looking for a way to creating dynamic urls with kirby in order to render a random image from the array of images in my contact page contents folder

I was thinking something like this might work but no luck
var bg = [’<?= $page->images() ?>’];

Here is my code which works fine but looking to not use static urls

function change() {
var bg = ['content/5_contact/dawn.jpg', 'content/5_contact/galore.jpeg'];

    'background' : 'url('+ bg[Math.floor(Math.random() * bg.length)] + ') no-repeat', 'background-size' : 'cover', 'background-position': 'center'



You can provide the image url in a data attribute:

$randomImage = $page->images()->shuffle()->first();
$randomImageUrl = $randomImage ? $randomImage->url() : '';

<div class="contact__image" data-image="<?= $randomImageUrl() ?>">Some stuff here</div>

Then fetch the attribute in your JS.

But you might as well just add the background image via inline styles, no need for JS

<div class="contact__image" style="background-image:url(<?= $randomImageUrl ?>)">Some stuff here</div>
1 Like

This works perfectly! Thank you