#Use functions defined within regular scripts in inline scripts
8 messages · Page 1 of 1 (latest)
Hi @clear bronze. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Based on the information provided in the extracts, Astro allows you to include both regular and inline scripts on your page. However, it doesn't explicitly mention the ability to use functions defined in regular scripts within inline scripts on the same page.
Regular scripts can be included in your Astro components using the <script> tag's src attribute. These scripts will be built, optimized, and added to the page by Astro. For example:
<!-- relative path to script at `src/scripts/local.js` -->
<script src="../scripts/local.js"></script>
Source: Astro Documentation (https://docs.astro.build/en/guides/client-side-scripts#include-javascript-files-on-your-page)
Inline scripts can be added using the is:inline directive. This tells Astro to leave the script as-is in the final output HTML, without processing, optimizing, or bundling it. For example:
<script is:inline>
// Will be rendered into the HTML exactly as written!
// Local imports are not resolved and will not work.
// If in a component, repeats each time the component is used.
</script>
Source: Astro Documentation (https://docs.astro.build/en/guides/client-side-scripts#opting-out-of-processing)
However, the extracts do not provide specific information on whether functions defined in regular scripts can be used within inline scripts on the same page. It's worth noting that the behavior of scripts in a web page can depend on various factors such as the order of script loading and execution, scope of variables and functions, and browser's same-origin policy.
For more detailed information, you may want to refer to the Astro Documentation (https://docs.astro.build/) or ask in the Astro GitHub Discussions (https://github.com/withastro/astro/discussions) for community support.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@clear bronze kapa.ai is still learning and improving, please let us know how it did by reacting below
<@&1095491216776380548> this is possible by defining the functions as part of the window, EG:
window.scrollWindowBasedOnMousePosition = (event) => {
const overflowX = document.body.scrollWidth - window.innerWidth
const overflowY = document.body.scrollHeight - window.innerHeight
if (event != undefined) {
relativeX = event.clientX / window.innerWidth * 1.4 - 0.2
relativeY = event.clientY / window.innerHeight * 1.4 - 0.2
}
window.scrollTo(overflowX * relativeX, overflowY * relativeY)
}
You can then define the inline script as a module, and use the function: