Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a javascript function from another .js file

I have two external .js files. The first contains a function. The second calls the function.

file1.js

$(document).ready(function() {      function menuHoverStart(element, topshift, thumbchange) {          ... function here ...      }   }); 

file2.js

$(document).ready(function() {      setTimeout(function() { menuHoverStart("#myDiv", "63px", "myIMG"); },2000);   }); 

The trouble is that this is not running the function. I need the two separate files because file2.js is inserted dynamically depending on certain conditions. This function works if I include the setTimeout... line at the end of file1.js

Any ideas?

like image 805
Tom Avatar asked Dec 02 '10 12:12

Tom


People also ask

Can you call a function from another file JavaScript?

A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it. A function cannot be called unless it is in the same or greater scope then the one trying to call it.

How do I link two JavaScript files?

Answer: Use the export and import Statement Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.


1 Answers

The problem is, that menuHoverStart is not accessible outside of its scope (which is defined by the .ready() callback function in file #1). You need to make this function available in the global scope (or through any object that is available in the global scope):

function menuHoverStart(element, topshift, thumbchange) {     // ... }  $(document).ready(function() {     // ... }); 

If you want menuHoverStart to stay in the .ready() callback, you need to add the function to the global object manually (using a function expression):

$(document).ready(function() {     window.menuHoverStart = function (element, topshift, thumbchange) {         // ...     };     // ... }); 
like image 54
jwueller Avatar answered Sep 17 '22 16:09

jwueller