I created an AS3 script with a function
public function sayHello():String
{
return "Hello";
}
I have also registered the callback as follows
ExternalInterface.addCallback("sayHello", sayHello);
In my javascript, I have embedded the SWF file as follows
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
swfobject.embedSWF("HelloWorld.swf", "HelloWorld", "1", "1", "9.0.0");
</script>
But when I try to call the sayHello method as follows
document.getElementById("HelloWorld").sayHello();
I am getting Uncaught TypeError: Cannot call method 'sayHello' of undefined
Any help will be appreciated!
If the swf isn't loaded yet then document.getElementById("HelloWorld") will return undefined hence your error. You can try if this is the case by calling that couple seconds later.
setTimeout(function() {
document.getElementById("HelloWorld").sayHello();
},5000);
I would also put that code inside a function that is called on body onload event ie.
...
<head>
<script>
function onload() {
setTimeout(function() {
document.getElementById("HelloWorld").sayHello();
},5000);
}
</script>
...
</head>
<body onload="onload()">
...
</body>
Related
I wanted to call a function defined in a first.js file in second.js file. Both files are defined in an HTML file like:
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
I want to call fn1() defined in first.js in second.js. From my searches answers were if first.js is defined first it is possible, but from my tests I haven't found any way to do that.
Here is my code:
second.js
document.getElementById("btn").onclick = function() {
fn1();
}
first.js
function fn1() {
alert("external fn clicked");
}
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.
You declare function fn1 in first.js, and then in second you can just have fn1();
1.js:
function fn1 () {
alert();
}
2.js:
fn1();
index.html :
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
You could consider using the es6 import export syntax. In file 1;
export function f1() {...}
And then in file 2;
import { f1 } from "./file1.js";
f1();
Please note that this only works if you're using <script src="./file2.js" type="module">
You will not need two script tags if you do it this way. You simply need the main script, and you can import all your other stuff there.
1st JS:
function fn(){
alert("Hello! Uncle Namaste...Chalo Kaaam ki Baat p Aate h...");
}
2nd JS:
$.getscript("url or name of 1st Js File",function(){
fn();
});
You can make the function a global variable in first.js
and have a look at closure and do not put it in document.ready put it outside
you can use ajax too
$.ajax({
url: "url to script",
dataType: "script",
success: success
});
same way you can use jquery getScript
$.getScript( "ajax/test.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
declare function in global scope with window
first.js
window.fn1 = function fn1() {
alert("external fn clicked");
}
second.js
document.getElementById("btn").onclick = function() {
fn1();
}
include like this
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
use "var" while creating a function, then you can access that from another file. make sure both files are well connected to your project and can access each other.
file_1.js
var firstLetterUppercase = function(str) {
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
return str;
}
accessing this function/variable from file_2.js file
firstLetterUppercase("gobinda");
output => Gobinda
It should work like this:
1.js
function fn1() {
document.getElementById("result").innerHTML += "fn1 gets called";
}
2.js
function clickedTheButton() {
fn1();
}
index.html
<html>
<head>
</head>
<body>
<button onclick="clickedTheButton()">Click me</button>
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
</body>
</html>
output
Try this CodePen snippet: link .
Please note this only works if the
<script>
tags are in the body and NOT in the head.
So
<head>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</head>
=> unknown function fn1()
Fails and
<body>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</body>
works.
This is actually coming very late, but I thought I should share,
in index.html
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
in 1.js
fn1 = function() {
alert("external fn clicked");
}
in 2.js
fn1()
Use cache if your server allows it to improve speed.
var extern =(url)=> { // load extern javascript
let scr = $.extend({}, {
dataType: 'script',
cache: true,
url: url
});
return $.ajax(scr);
}
function ext(file, func) {
extern(file).done(func); // calls a function from an extern javascript file
}
And then use it like this:
ext('somefile.js',()=>
myFunc(args)
);
Optionally, make a prototype of it to have it more flexible. So that you don't have to define the file every time, if you call a function or if you want to fetch code from multiple files.
first.js
function first() { alert("first"); }
Second.js
var imported = document.createElement("script");
imported.src = "other js/first.js"; //saved in "other js" folder
document.getElementsByTagName("head")[0].appendChild(imported);
function second() { alert("Second");}
index.html
<HTML>
<HEAD>
<SCRIPT SRC="second.js"></SCRIPT>
</HEAD>
<BODY>
method in second js<br/>
method in firstjs ("included" by the first)
</BODY>
</HTML>
window.onload = function(){
document.getElementById("btn").onclick = function(){
fn1();
}
// this should work, It calls when all js files loaded, No matter what position you have written
});
// module.js
export function hello() {
return "Hello";
}
// main.js
import {hello} from 'module'; // or './module'
let val = hello(); // val is "Hello";
reference from https://hype.codes/how-include-js-file-another-js-file
My idea is let two JavaScript call function through DOM.
The way to do it is simple ...
We just need to define hidden js_ipc html tag.
After the callee register click from the hidden js_ipc tag, then
The caller can dispatch the click event to trigger callee.
And the argument is save in the event that you want to pass.
When we need to use above way ?
Sometime, the two javascript code is very complicated to integrate and so many async code there. And different code use different framework but you still need to have a simple way to integrate them together.
So, in that case, it is not easy to do it.
In my project's implementation, I meet this case and it is very complicated to integrate. And finally I found out that we can let two javascript call each other through DOM.
I demonstrate this way in this git code. you can get it through this way. (Or read it from https://github.com/milochen0418/javascript-ipc-demo)
git clone https://github.com/milochen0418/javascript-ipc-demo
cd javascript-ipc-demo
git checkout 5f75d44530b4145ca2b06105c6aac28b764f066e
Anywhere, Here, I try to explain by the following simple case. I hope that this way can help you to integrate two different javascript code easier than before there is no any JavaScript library to support communication between two javascript file that made by different team.
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div id="js_ipc" style="display:none;"></div>
<div id="test_btn" class="btn">
<a><p>click to test</p></a>
</div>
</body>
<script src="js/callee.js"></script>
<script src="js/caller.js"></script>
</html>
And the code
css/style.css
.btn {
background-color:grey;
cursor:pointer;
display:inline-block;
}
js/caller.js
function caller_add_of_ipc(num1, num2) {
var e = new Event("click");
e.arguments = arguments;
document.getElementById("js_ipc").dispatchEvent(e);
}
document.getElementById("test_btn").addEventListener('click', function(e) {
console.log("click to invoke caller of IPC");
caller_add_of_ipc(33, 22);
});
js/callee.js
document.getElementById("js_ipc").addEventListener('click', (e)=>{
callee_add_of_ipc(e.arguments);
});
function callee_add_of_ipc(arguments) {
let num1 = arguments[0];
let num2 = arguments[1];
console.log("This is callee of IPC -- inner-communication process");
console.log( "num1 + num2 = " + (num1 + num2));
}
better late than never
(function (window) {const helper = { fetchApi: function () { return "oke"}
if (typeof define === 'function' && define.amd) {
define(function () { return helper; });
}
else if (typeof module === 'object' && module.exports) {
module.exports = helper;
}
else {
window.helper = helper;
}
}(window))
index html
<script src="helper.js"></script>
<script src="test.js"></script>
in test.js file
helper.fetchApi()
I have had same problem. I have had defined functions inside jquery document ready function.
$(document).ready(function() {
function xyz()
{
//some code
}
});
And this function xyz() I have called in another file. This doesn't working :) You have to defined function above document ready.
TLDR: Load Global Function Files first, Then Load Event Handlers
Whenever you are accessing an element within a JS file or <script> block, it is essential to check to make sure that element exists, i.e., jQuery's $(document).ready() or plain JS's document.addEventListener('DOMContentLoaded', function(event)....
However, the accepted solution does NOT work in the event that you add an event listener for the DOMContentLoaded, which you can easily observe from the comments.
Procedure for Loading Global Function Files First
The solution is as follows:
Separate the logic of your JS script files so that each file only contains event listeners or global, independent functions.
Load the JS script files with the global, independent functions first.
Load the JS script files with event listeners second. Unlike the other previous files, make sure to wrap your code in document.addEventListener('DOMContentLoaded', function(event) {...}). or document.Ready().
I'm woking on a ASP.NET project and im trying to use the attr function,
when im putting in the script tag the src for the jquery file the function isnt being called when im calling it via c# code.
<script type ="text/javascript" src="jquery-3.1.1.min.js">
$(document).ready(function () {
function startGame(path) {
alert(path);
$("#test").attr("style", "color:Blue");
$("#game_param").attr("value", path);
$("#game_embed").attr("src", path);
}
});
</script>
I tried to write a simple javascript fucntion
<script type ="text/javascript" src="jquery-3.1.1.min.js">
function startGame(a) {
alert(a);
}
</script>
and it wasn't called either
im getting en error that startGame isn't defined, in both cases.
can someone expain to me what im doing wrong?
You need to include the jQuery source separately from your custom code. Otherwise I believe what is inside of the script tag is ignored.
<script type ="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var p = 'here/is/my/path';
function startGame(path) {
alert(path);
$("#test").attr("style", "color:Blue");
$("#game_param").attr("value", path);
$("#game_embed").attr("src", path);
}
startGame(p);
});
</script>
Your Javascript isn't correct.
When you do:
<script type ="text/javascript" src="jquery-3.1.1.min.js">
function startGame(a) {
alert(a);
}
</script>
You're setting the source of the JavaScript file to be the jQuery JS file. If you want to define your own functions, you have to put it in its own script tag, like so:
<script type ="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function startGame(a) {
alert(a);
}
</script>
You actually have multiple errors.
Browsers will ignore any javascript written inside a script tag that has a src attribute. So you need to include jQuery separately, like so:
<script type ="text/javascript" src="jquery-3.1.1.min.js"></script>
<script>
// Your code here.
</script>
You're never actually calling the function, only declaring them. If you're only going to use this once, you don't even need a function:
<script type ="text/javascript" src="jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function () {
alert(path);
$("#test").attr("style", "color:Blue");
$("#game_param").attr("value", path);
$("#game_embed").attr("src", path);
});
</script>
Otherwise, you need to call the function after declaring it like so:
$(document).ready(function () {
function startGame(path) {
// Your code
}
startGame();
});
Function Declarations vs Expressions
From the documentation I understood that in order to change the language of the recaptcha I have to render it explicitly.
The problem is, however, that it's not really showing up, and the onload is not even called.
When I try to render it automatically it does work.
Here's the code:
In the HTML head: (I have also tried putting this at the end of the body tag)
<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&hl=iw" async defer></script>
In the HTML form:
<div id="recaptcha"></div>
Javascript:
var recaptchaCallback = function() {
console.log('recaptcha is ready'); // not showing
grecaptcha.render("recaptcha", {
sitekey: 'My Site Key',
callback: function() {
console.log('recaptcha callback');
}
});
}
I just copied your code, used my own Site Key and it works.
The code I used is:
<html>
<body>
<p>ReCaptcha Test</p>
<div id="recaptcha"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&hl=iw" async defer></script>
<script type="text/javascript">
var recaptchaCallback = function () {
console.log('recaptcha is ready'); // showing
grecaptcha.render("recaptcha", {
sitekey: 'SITE_KEY',
callback: function () {
console.log('recaptcha callback');
}
});
}
</script>
</body>
</html>
Check your code carefully, as just a single character typo can stop things from working.
Make sure that your onload method is defined before the recaptcha script. Otherwise you will have a race condition where the recaptcha script could be attempting to call your method before it is defined (especially if the recaptcha script is cached).
From the documentation for onload https://developers.google.com/recaptcha/docs/display
Note: your onload callback function must be defined before the
reCAPTCHA API loads. To ensure there are no race conditions:
order your scripts with the callback first, and then reCAPTCHA
use the async and defer parameters in the script tags
For example:
<div id="recaptcha"></div>
<script type="text/javascript">
var recaptchaCallback = function () {
console.log('recaptcha is ready'); // not showing
grecaptcha.render("recaptcha", {
sitekey: 'SITE_KEY',
callback: function () {
console.log('recaptcha callback');
}
});
}
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&hl=iw" async defer></script>
My problem was that I did not realise that the second callback is only fired upon submission of the form - whereas the first callback is executed on page load.
HTML
<div id="captcha"></div>
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaReadycallback&render=explicit' async defer'></script>
JavaScript
// Render captcha and set call back function on api.js load finish
function recaptchaReadycallback(){
grecaptcha.render('captcha', {
'callback' : recaptchaCheckedCallback,
'expired-callback': recaptchaExpiredCallback,
'sitekey': 'YOUR-SITE-KEY'
});
}
// On expiry do stuff. E.g. show error
function recaptchaExpiredCallback(){
grecaptcha.reset();
// Show 'check the bloody box' error
};
// On not a robot confirmation do stuff. E.g. hide error
function recaptchaCheckedCallback(){
// Hide 'check the bloody box' error
}
I have JS file with uploader functionality.
This file called from an iframe window.
I need to show alerts to user according to his actions.
Here is what I've done and it's not works:
From JS file:
$('#btnUpload').on('click', function(){
parent.CallToParent();
});
And from UploaderWindow call to:
function CallToParent()
{
parent.ShowAlert();
}
And on main window:
function ShowAlert()
{
alert('some alert');
}
I think you are doing it correct. Don't know if the parent.CallToParent() in the click event really refers to the function in the parent window. If it doesn't then you could do something like.
From JS file:
$(document).ready(function () {
$('#btnUpload').on('click', function() {
callParent();
})
});
And from iframe:
<script type="text/javascript" src="/common/jq.js"></script>
<script type="text/javascript" src="c.js"></script>
<script>
function callParent() {
parent.fn();
}
</script>
<input id="btnUpload" type="button" />
Main File
<script>
function fn() {
console.log('Parent function called');
}
</script>
<iframe src="b.html"></iframe>
To my knowledge, there's no interoperability of scripts between these two contexts.
If you have control of the iframe contents then you could implement a 'middle-man' service to pipe messages.
I think the pop window with OK string will be dislayed afetr 5s after I click the button, but the pop window dispalyed immediately after I click the button, why?
Thanks!
<html>
<head>
<title>Wake up call</title>
<script type="text/javascript">
function wakeUpCall() { // Function is defined here
setTimeout(aa("ok"), 5000);
}
function aa(bb) {
alert(bb);
}
</script>
</head>
<body bgcolor="lightblue">
<form>
<input type="button"
value="Wake me"
onclick="wakeUpCall()">
</form>
</body>
</html>
function wakeUpCall() { // Function is defined here
setTimeout(function(){ alert("ok");}, 5000);
}
You are trying to do it the wrong way.
You have to use a callback for the setTimeout:
setTimeout(function()
{
// actual code here
}, 5000);
Mike has provided in his answer - that you could use an evaluatable string:
setTimeout('/* actual code here */', 5000);
But that is strongly discouraged, use his other example - passing the callback function as a reference and invoking callback arguments.
You have to take in mind, though, that if you are going with callback arguments, see this section of MDN article. The callback arguments aren't supported in all browsers.
Personally, I'd suggest going with plain old callbacks, because that's how the setTimeout is meant to be used.
Just for your information:
The reason why your snippet isn't working for you, is, because:
setTimeout(aa('ok'), 5000);
// aa('ok') here is executed, and returns its value, so, in the end, you pass the returned value of aa inside the Timeout.
// and, nor alert alert, nor your function have a "return" statement, so they both will return always undefined.
// that translates to:
setTimeout(undefined, 5000); // and, that does nothing
What if you would do it like this:
<html>
<head>
<title>Wake up call</title>
<script type="text/javascript">
function wakeUpCall() { // Function is defined here
setTimeout('aa("ok");', 5000);
}
function aa(bb) {
alert(bb);
}
</script>
</head>
<body bgcolor="lightblue">
<form>
<input type="button"
value="Wake me"
onclick="wakeUpCall()">
</form>
</body>
</html>
Notice I have quoted the statement to execute in the setTimeout function. It those quotes confuse you, I think this is a good resource to take a look at: https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout
Another way to do it, I just learned from the resource above, is like this:
function wakeUpCall() { // Function is defined here
setTimeout(aa, 5000, "Your tekst here");
}
Use anonymous functions for this.
<html>
<head>
<title>Wake up call</title>
<script type="text/javascript">
function wakeUpCall() { // Function is defined here
setTimeout(function(){aa("ok");}, 5000);
}
function aa(bb) {
alert(bb);
}
</script>
</head>
<body bgcolor="lightblue">
<form>
<input type="button"
value="Wake me"
onclick="wakeUpCall()">
</form>
</body>
</html>