1

I have a really simple function:

function loading (text, id) {
    console.log("test");
    $('#loadingsts').append('<div id="loader"></div>');
}

that is defined in a javascript file which is loaded with the html via:

<script src="js/loader.js"></script>.

I want to execute that function in another js file so I need to have the function be global, right?

If I execute is like this, the console.log() works but the but the append doesn't. If I put the function into a $(function() {}); it says loading() not defined.

I also don't want the function to be executed on loading but only when called.

How can i make it work. I looked at these questions already but they didn't help

jjbbss
  • 139
  • 2
  • 15

1 Answers1

3

A method created outside any other method is global by nature. If you are creating a method inside another method, you can make it global by attaching it to the window object if you like, or another object that is global itself, in which case you'd have to access it by thatObject.yourMethod()

var objectOutsideAnyMethod = {};
(function(){
    function ImNotGlobal(){}

    window.IAmGlobal = function() {};
    objectOutsideAnyMethod.meToo = function(){};
})();

IAmGlobal(); //valid
objectOutsideAnyMethod.meToo(); //valid
ImNotGlobal(); //error
Taplar
  • 24,788
  • 4
  • 22
  • 35
  • I tried the window.loader_status, and as before it does print he console.log but does not append(). – jjbbss Aug 22 '17 at 22:07
  • but it is definitely there `
    ` is in the html body
    – jjbbss Aug 22 '17 at 22:11
  • that's why i put everything in the `$(function(){});`. that should guarantee that, right? but then after i write window.loader_status to make it global even in the ready function, it still doesn't append – jjbbss Aug 22 '17 at 22:22
  • `$('#loadingsts').length` gives me 1 – jjbbss Aug 22 '17 at 22:24
  • yes, i executed it from inside the loader_status method. the same place where the console log was before. but still no appending – jjbbss Aug 22 '17 at 22:29
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/152577/discussion-between-user5236815-and-taplar). – jjbbss Aug 22 '17 at 22:29