Site logo

Archived topic

Call js function globally

5 replies · Started by Stefan on February 22, 2021

Viewing posts 1–6 of 6

Hi there!

I'm using a handful of different element hooks to include differing JS code depending on the page the user is on.

However, within those different hooks I need to call commonly shared JS functions (e.g. a function for efficient cookie setting) and I'm looking for a solution so that I don't have to include (and later potentially update) said functions over and over within every single hook. Instead I'd like to have said functions in a single spot and call this "global" spot from within the indiviual, page-specific hooks.

Any ideas?

Thanks in advance!
Stefan

Hi there,

i am not sure i follow - so you have a global function eg. set_cookie_function that you want to pass different values to depending on the page you're on ?

Hi David,

eventually yes. However, I first need to know how create the function in the first place so that is also accessible from any other hook element in my element portfolio.

You have a couple of choices:

1. Create a Hook for all your Global scripts and set this to the Entire Site ( or wherever ).
2. Create a function in your child theme functions.php and call that function function from your page specific hooks.

The latter is the more logical way to do it as you can more easily pass variables to that function

Thank you David!

Adding JS to my functions.php apparently was blocked by our clearfy plugin, so I went for your approach #1, i.e. creating a global hook and accessing its functions with "window.myFunctionName(myVar)". This seems to work!

Glad to hear that!

This archived topic is closed to new replies.