Display random content on each new hover

I’m trying to make a new image to appear each time the mouse exits and re-enters an element. I’ve managed to allow an image to appear on mouse hover and disappear on mouse exit using jQuery, but I can’t get the image to be different on each new hover. I’ve used the ->shuffle() function, but this only works when the page is refreshed.

I managed to get a new image to appear on each hover using jQuery, but the issue is that I can’t add kirby codes to the array.

Hope this makes sense, please let me know if I can supply any other useful information.

Exactly, what you need to get a fresh image from the server is an Ajax request that is triggered on mouse hover event.

Or you would have to load all images in advance and then do the shuffling in the client. But the first option makes more sense IMO.

Thank you! Would you be able to point me in the right direction for working with Ajax requests in kirby? Many thanks

Basically, you can either work with content representations (call your content representation in the Ajax call) or use routes that return something when called via Ajax.

1 Like

Apologies for being a deeply lost noob, please let me know if this isn’t appropriate.

I’ve set up a test.json.php file with this content:

<?php $data = [
 'test'  => $images = page('images')->images()->shuffle()->first()
    ];

echo json_encode($data);

How would I access this with an Ajax call? I’ve tried following a few other examples in the forum using content representations and I truly don’t understand. Again, my apologies :frowning:

For the content representation to work, you need a page folder, your best bet would be to create a content representation for the page where you are showing the images. E.g. if your images are on a projects page and the template used to render the content of that page is projects.php, then create a projects.json.php as content representation.