Pankaj Shinde Pankaj Shinde - 4 years ago 119
Javascript Question

Call .js function in another.js

I have...

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="xpath.js"></script>
<script src="myscript.js"></script>
</head>
<body>
<!-- some html code -->
</body>
</html>


myscript.js

$( document ).ready(function() {
$("body").click(function(event){
console.log(event.target);
//call xpath.js (getxpath(event.target))
});
});


xpath.js

here stored locally

How do I achieve this..?

Answer Source

Accessing functions from another file

Code separation between files does not matter (You could pack them all in a single file without any problem). Execution order and scopes do. All scripts loaded on a web page share a same global scope, which is window, and can add variables to it.

Most libraries do this so you can access them (jQuery creates a global $ variable, for example, and you can use it anywhere).

Your Xpath script, however, does not, because it's not meant to be directly embedded into a webpage. It's part of a Firefox addon. So in order to make it accessible, you need to modify it.

Modifying xpath.js

At the beginning, change this:

define([
    "firebug/lib/string"
],
function(Str) {

... to this:

window.Xpath = new (function(Str) {

And at the end, change this:

});

... to this:

})();

Using it

Now that you did this, you have a global Xpath Object that you can access like this:

$(function() {
   $("body").click(function(event){
       console.log(Xpath.getElementXPath(event.target));
   });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download