Using php page informations in javascript

Hi there,
I’ve started using Kirby quite recently and I’m very new to all of this.
Here is a simplified example of the situation i’m in:
I’m able to use informations like <?= $image->title()?>"> quite simply in my html.
But now, i’m making a script that will react when you hover an image.
So I’d like the user to be able to hover any image and be alerted of that image title.

$("img").hover(function () {
  alert("<?= $image->title()?>");
});

but it’s not working the way i’d like, obviously. the output is : <?= $image->title()?>
I might be missing something but I’m asking for help since I don’t know what.

Thanks a lot.

You can make use of Kirby’s JSON::encode and create a javascript object with all the data you need. Maybe something like this (not tested):

<?php

$data = JSON::encode([
    'title' => $image->title(),
]);

?>
<script>
const data = <?= $data ?>

$("img").hover(function () {
  alert(data.title);
});
</script>

thanks for the help.
Unfortunately, I’m not sure this is working since the console is giving me this error :
Uncaught SyntaxError: expected expression, got '<'
as I add the new const.

I think it would make more sense to store this information in a data attribute in your HTML you can then reference in your script. That way, your JS can live in a script file. If you need more data, calling a route or content representation could be options

Hi, thanks for the help!
I’m not sure it’s very clear for me though…
Is there any documentation I could use, or an example ?

It looks like you’re trying to run PHP in a javascript or an HTML file. That won’t work unless you explicitly tell apache to execute .js / .html files as PHP (but you really shouldn’t).

In a kirby template:

<img <?= attr([
    'src' => $image->url(),
    'alt' => '',
    'class' => 'shout-on-hover'
    'data-title' => $image->title()
]) ?> />

In your javascript file:

$('img.shout-on-hover').hover(function() {
  alert($(this).data('title'))
})

Hi rasteiner,
Seems pretty clear now. I’ll investigate and dig around that.
It’s working and doing what I wanted it to do.
Any documentation I could read to try to understand that better?

Thanks.

There are different topics in my post:

  • There’s Kirby’s attr() function that formats and escapes HTML attributes for elements
  • There’s jQuery’s this in the hover handler, that refers to the event “target” that triggered the current jQuery event.
  • There’s jQuery’s data() function that reads and returns from attributes whose name begin with data-

And there’s the general concept about “when what is executed where and by whom”. I wouldn’t know a specific authoritative source online for that.
Maybe we can help you better with more specific questions. :slight_smile:

Keep in mind you can access the attributes with Vanilla JS too, without the weight of jQuery.