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..?
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));
});
});
Related
I am trying to execute a function from within a script. It shows no error but also doesnt execute the function.
file.mjs
function test() {
console.log("test")
}
This is my html:
index.html
<head>
<script type="module" src="file.mjs">
</head>
<body>
<button type="button" id="Submit">Submit</button>
<script>
document.getElementById('Submit').addEventListener('click', test);
</script>
</body>
This worked fine using 2 separate scripts, to make it global I was using type="text/javascript".
But since my file.mjs is actually importing a library I had to set it as type="module" and the function wont execute. Is there a way to make the module scope global?
Before I go on, there's a big problem that needs addressing:
Your syntax is wrong. If you want to import a script, that tag must have the src attribute and nothing within the tag. If you want to execute an "inline" script, it should NOT have the src attribute, so what you should have is two script tags, one to import the module, the other to execute your inline code.
Now, I'm not sure what you mean by "global". To obtain true "globalness", you would have to define your variable in the global object (window or globalThis) like so:
// file.mjs
function test() { ... }
window["test"] = test;
Then in your regular script you could just do document.getElementById('Submit').addEventListener('click', test);.
That sort of completely destroys the purpose of JS modules though, as it's supposed to be an "import/export" model.
Ignoring the "global" part of your question: if you want to use modules for what they're worth, you would be importing and exporting them, and you would only (almost always) link a <script type="module"> in your HTML if it only imports and never exports (exporting would be useless). The reason you need type="module" is to tell the browser that you're operating on modules so it'll allow you to import/export. With that said, your code would look like this:
// file.mjs
export function test() { ... }
And in your HTML, you would only need one script tag (that goes right before the ending body tag):
<script type="module">
import { test } from "/path/to/file.mjs";
document.getElementById('Submit').addEventListener('click', test);
</script>
I hope that clears it up for you, and docs if you need them.
I am working with the MVC4 application with the aid of an external js file. In the view (.cshtml) file, I have a function which performs an action of creating the row in the grid,
based on the button click.
I have defined the button click in the external .js file.
But, when I tried to call the internal script function from that external js file method, it throws an exception saying that, that particular method is not defined.
I surfed but was not able to find a convincing answer..
Is what I'm trying possible??.. How should I achieve it??
Can any Js expert out there help me with this?...
Thanks All...;)
EDIT:
this is in external .js file:
$('#AddRowButton').on('click', function () {
window.CreateRow();
}
in my view:(.cshtml)
<script>
function CreateRow()
{
// creting row goes here...
}
window.CreateRow = CreateRow; //defined like what #joseeight suggested...
</script>
This is most likely due to a scoping issue. The internal script and external must be in a different scopes. The easiest, and hackiest, way to get around this would be to add the internal method to the Window, and access it as such in the external.
//Internal script
function myInternalMethod () {
//some code..
}
window.myInternalMethod = myInternalMethod;
Since window is global, and the name is the same, you could either use window.myInternalMethod or myInternalMethod when referencing it in the external scripts.
Make sure your external file is included below the internal
.......
<script>
function createRow(){
console.log('created');
}
</script>
<script src = "external.js"></script>
</body>
yes it is possible only when you call that external js file from html where that internal javascript have..
Example :
a.html
<html>
<head>
<script type="text/javascript">
function displayAlert(){
alert('displayAlert');
}
</script>
<script type="text/javascript" src="../../abc.js"></script>
</head>
<body>
//call the sample() javascript function which is in abc.js
</body>
</html>
abc.js
function sample(){
displayAlert();
}
i've seen the other posts in regard to this, but the following method is not working for some reason.
onclick="parent.testing();"
now for the full story. i have an index.html that houses all the JS files. also within the index, i have an empty 'div' tag. with jQuery, i'm appending a page1.html file to the empty 'div'. so the index kinda looks like this:
<html>
<head>
<script files>
<script>
ready { function testing(){do stuff;} }
</script>
</head>
<body>
<div><iframe src="page1.html" (added via jQuery)></div>
</body>
</html>
now in the page1.html file, i'm trying to call a function when a link is clicked. but i'm receiving the following error:
Uncaught TypeError: Cannot call method 'testing' of undefined
i've also tried the following but they didn't work:
onclick="window.testing();"
onclick="window.frames[0].testing();"
Your parent page script isn't valid JavaScript, but assuming ready { ... }:
<script>
ready { function testing(){do stuff;} }
</script>
...is a simplification supposed to represent a document ready handler you are declaring testing() as a local function within that ready handler so it can only be accessed from within that ready handler. You need to make testing() global in the parent page:
<script>
$(document).ready({ /* your on ready stuff here */ });
function testing(){ /* do stuff; */ }
</script>
...and then you should be able to call it from the iframe using parent.testing().
If I understand your question, your problem it's your function is not called, right? So maybe a solution is to put this in your "page1.html"
<script type="text/javascript" src="your_js_file"></script>
I am trying to load 2 javascript events/functions in the body onload as follows :-
<body onLoad="getSubs(document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value);getTags(document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value);">
Whenever I load using 2 functions the first one aborts - but if I just load the one it works fine - am I doing something wrong is it no possible to put 2 functions within the onload?
try this:
<html>
<head>
<script language="javascript">
function func1(){
//the code for your first onload here
alert("func1");
}
function func2(){
//the code for your second onload here
alert("func2");
}
function func3(){
//the code for your third onload here
alert("func3");
}
function start(){
func1();
func2();
func3();
}
</script>
</head>
<body onload="start()">
</body>
</html>
Multiple onload
Just do it from java script instead, one of the link shared into a comment explains well why it is best to use this approach over inline attributes.
<head>
<script>
document.body.onload = function() {
getSubs(...);
getTags(...);
};
</script>
</head>
<body>
...
</body>
I would avoid at all cost to have inline javascript, that is what you did in the code of your question: add javascript within an HTML attribute.
Best practice is to add your javascript in a separate file, see the related question on this principle What is Unobtrusive Javascript in layman terms?
So you'd have an other file called for instance "myjsfile.js", then you reference it from your HTML page
<script src="./path/to/your/myjsfile.js"></script>
Here is the answer to where to place this reference: Where to place Javascript in a HTML file?
Your "myjsfile.js" file would simply have:
window.onload = function(){
getSubs(...);
getTags(...);
};
Another thing to avoid: add javascript within the same HTML file. The reason is also based on the same principle of unobstrusive javascript. What is Unobtrusive Javascript in layman terms?
But I guess there are corner cases where you may want to do that.
If you really have to, do use window.onload instead of the inline javascript onload="...", see why here window.onload vs <body onload=""/>
Just add the following to your HTML file:
<script type="text/javascript">
window.onload = function(){
getSubs(...);
getTags(...);
};
</script>
Here is the answer to where to place this code: Where to place Javascript in a HTML file?
Note: Yes, in the same place as where you would put the reference to an external javascript file
Another thing: I do not know where your getSubs() and getTags() functions are defined. But if you want your code to work, it needs to call these functions after the file (or part of javascript) that defines them has been loaded.
In short: make sure the javascript file containing the definitions of getSubs() and getTags() is referenced before your code.
One thing that you could do is create a new JS function that accepts the document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value parameter and call the two functions in the newly created function.
I tried calling two functions using the below code and it worked fine for me.
<html>
<body onload="callStart();callAgain();">
<script type="text/javascript">
function callStart() {
alert('First');
}
function callAgain() {
alert('Again');
}
</script>
</body>
</html>
I've a Utils class in JavaScript. Below is the source code of that JavaScript.
function UtilityMethod(){
this.testMethod=function(){
alert("Test method is called");
}
}
Above code is included in Utils.js file.Now I need to create an instance of UtilityMethod in my HTML File. I've referenced Utils.js in my HTML file. Below is my HTML Code.
<html>
<head>
<title> New Document </title>
<script type="text/javascript" src="/dojo/dojo.js"></script>
<script type="text/javascript" src="/js/Utils.js"></script>
</head>
<body>
<script type="text/javascript">
dojo.addOnLoad(function(){
var Utils = new UtilityMethod();
});
</script>
TestMethodCall
</body>
</html>
But when I click on the HyperLink, it is giving me the error Utils is not defined. But even though I'm clicking on the link after page load, why is it still giving the error?
I need to include the instance creation in dojo.addOnLoad() method. Can you please suggest if there are other easy alternatives to this?
I know that we can do this using dojo.connect(), but is there another approach to do this. If we are using dojo.connect, we have to make changes to lot of code.
It's because Utils is created in a function; it won't be available outside the function. A nice explanation of this scoping behavior can be found here. To make this work, you'll need to tell the browser that Utils is a global variable:
window.Utils = new UtilityMethod();
Now, Utils is set on the window object thus making it accessible anywhere (A nice feat of the window object is that its properties are available without the window. prepended, so you can still use Utils.testMethod as normal)