I have some links on my site which currently uses alpine.js to trigger a function that scrolls to a div on the page and I wish to convert this to use Datastar.js
This is what is currently in the base.html file and the javascript file.
base.html
<div class="flex h-full items-end py-4 gap-x-14 text-white uppercase text-xs font-medium">
<div><a href="#" x-on:click.prevent="scrollToId('contact')">Contact Us</a></div>
<div><a href="#" x-on:click.prevent="scrollToId('about')">About us</a></div>
<div><a href="#" x-on:click.prevent="scrollToId('services')">Services</a></div>
<div><a href="#" x-on:click.prevent="scrollToId('products')">Products</a></div> </div>
The javascript function is as follows and is imported into index.js then ran through webpack.
export default () => ({
scrollToId(id) {
// This is used for the navigation links in the header and footer
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({behavior: 'smooth' });
}
},
});
I have tried to convert this to Datastar data-on-click and run the 'scrollToId' function but it errors out saying it can't find the function.
<div><a href="#" data-on-click__prevent="scrollToId('contact')">Contact Us</a></div>
127.0.0.1/:10 GET http://127.0.0.1:8000/assets/components/smoothScroll.js net::ERR_ABORTED 404 (Not Found)
init_embed.js:285 Search endpoint requested!
backend.js:2 Alpine Devtools: waiting for init request...
datastar.js:8 Uncaught datastar runtime error: ExecuteExpression
More info: https://data-star.dev/errors/runtime/execute_expression?metadata=%7B%22plugin%22%3A%7B%22name%22%3A%22on%22%2C%22type%22%3A%22attribute%22%7D%2C%22element%22%3A%7B%22id%22%3A%22%22%2C%22tag%22%3A%22A%22%7D%2C%22expression%22%3A%7B%22rawKey%22%3A%22onClick__prevent%22%2C%22key%22%3A%22click%22%2C%22value%22%3A%22scrollToId%28%27contact%27%29%22%2C%22fnContent%22%3A%22scrollToId%28%27contact%27%29%22%7D%2C%22error%22%3A%22scrollToId+is+not+defined%22%7D
Context: {
"plugin": {
"name": "on",
"type": "attribute"
},
"element": {
"id": "",
"tag": "A"
},
"expression": {
"rawKey": "onClick__prevent",
"key": "click",
"value": "scrollToId('contact')",
"fnContent": "scrollToId('contact')"
},
"error": "scrollToId is not defined"
}
at pt (webpack://website/./assets/datastar.js?:8:1275)
at Number.mt (webpack://website/./assets/datastar.js?:10:330)
at On.e.runtimeErr.error (webpack://website/./assets/datastar.js?:11:876)
at HTMLAnchorElement.c (webpack://website/./assets/datastar.js?:11:9090)
pt @ datastar.js:8
mt @ datastar.js:10
On.e.runtimeErr.error @ datastar.js:11
c @ datastar.js:11
I really can't find anything in relation to doing this.
Apologies in advanced if I am missing something simple.
<a href="#contact" >+ developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior