Jump to content

JS - Calling functions between stripts, inside and outside of document.ready

Run into a problem where I need a function that is outside the document.ready to call a function that is inside it. 

$(document).ready(function () {
  function ExampleDoStuff(var message){
    		alert(message);
  }
});

function CalledExternally(){
	ExampleDoStuff("Do Stuff");
}

 

Ideally I'd have everything inside the ready script but I need the other function to be called by a different JS file, that also exists on the browser page, I couldn't call it if it was inside the scope of ready but could if it was outside.

 

I can think of two fixes:

  1. How can I place CalledExternally inside the ready and for it to be easily called by different JS files without the files explicitly referencing THIS file?
  2. If not, how can I get the code above to work. Online says to make the ready an class, doesn't work so I guess I keep doing it wrong?

Desktop: Ryzen 7 5800X3D - Kraken X62 Rev 2 - STRIX X470-I - 3600MHz 32GB Kingston Fury - 250GB 970 Evo boot - 2x 500GB 860 Evo - 1TB P3 - 4TB HDD - RX6800 - RMx 750 W 80+ Gold - Manta - Silent Wings Pro 4's enjoyer

SetupZowie XL2740 27.0" 240hz - Roccat Burt Pro Corsair K70 LUX browns - PC38X - Mackie CR5X's

Current build on PCPartPicker

 

Link to comment
Share on other sites

Link to post
Share on other sites

Fix for #2: Expose the needed function so that it's accessible by the code which needs it. e.g.:
 

function fnInit(arg) {
  //below line should be the first code in this function
  if (arg === "init") {
    //expose ExampleDoStuff function as fnInit's method
    fnInit.ExampleDoStuff = ExampleDoStuff;
    return;
  }
  
  function ExampleDoStuff(var message){
    alert(message);
  }
}
fnInit("init");
$(document).ready(fnInit);

function CalledExternally(){
  fnInit.ExampleDoStuff("Do Stuff");
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×