0

I have 2 jQuery files. In first, I have a variable definition. In second I want to load it.

#File 1:

$(document).ready(function(){
    //some jquery codes:
    windowWidth = $(window).width();
    windowHeight = $(window).height();
    
    //my variable:
    let myElements = [
        { top: windowHeight-100, left:windowWidth-100 }
        ...
    ];
});

#File 2:

$(document).ready(function(){
    ...
    // I need "myElements" variable from #File1 here!
    ...
});

HTML:

<head>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script src="js/file-1.js" type="text/javascript"></script>
    <script src="js/file-2.js" type="text/javascript"></script>
</head>

How I can load variable or functions from another jQuery file in my jQuery file?

I need "myElements" variable from #File1 in #File2.

Saeed sdns
  • 804
  • 7
  • 17
  • 2
    You could make it global (or namespaces as global not generally recommended). doc.ready's should be executed in the order they're defined, assuming there's no additional ajax to set the variable. In this case, I'd move the "file1" code to a `function` and call it as needed, but may not always be viable depending on the use-case (in this case it is) – freedomn-m Jan 29 '21 at 12:43
  • @freedomn-m In 'myElement' I use jquery codes, how I should use it as a global variable?! or how I can use it as a function? – Saeed sdns Jan 29 '21 at 12:50
  • 1
    `var myElements = []; $(function() { /*..*/ myElements = [ { top: ...` – freedomn-m Jan 29 '21 at 12:55
  • Thanks, it works. I define myElements as a global variable, then I use it in 2 files. – Saeed sdns Jan 29 '21 at 12:59

1 Answers1

1

if I understand it correctly, define 'myElements' out of scopes and its be global variables. Fill it with using 'push' or other methods. You can call it from other .js file

let myElements = [];
$(document).ready(function(){
//some jquery codes:
windowWidth = $(window).width();
windowHeight = $(window).height();
//my variable:
myElements.push(/*somthing*/)
    ];
});