How to call an external function internally in javascript? [duplicate] - javascript

This question already has answers here:
javascript <script> tag - code execution before src download
(4 answers)
Closed 8 years ago.
I am relatively new to JavaScript so this might be somewhat trivial. However I can't seem to find the answer to this question.
Say I have a JavaScript file (bar.js) with a function in it called foo(). I want to call this function (foo) inside a script tag. I would like it to work like so.
<script type="text/javascript" src="bar.js">
foo();
</script>
I am not able to get this to work. I have ran the JavaScript console with my browser and what it seems to be doing is...nothing. No syntax errors or anything.
I can run a function similarly with a button click...using the script tag above and this.
<button type="button" onclick="foo();">Click Me</button>
I could do it this way, but in the actual circumstance I need to pass parameters into the function that is being called on the button click. I can't get those recognized either. I'm sure that something to do with scope.
The way I tried this was like so...
<script type="text/javascript" src="bar.js">
var a = "blah";
var b = "blab";
</script>
.... (some more html)
<button type="button" onclick="foo(a,b);">Click me </button>
Here I get that a is undefined. Which leads me to think that it is a scope problem. The script tag is in the head section and the button is in the body section. Can you put script tags outside of the head and body tags to make global data?
Thanks for the help in advance.
I have never used jsfiddle before and was having trouble getting it to work so I'll just post and example code here.
<html>
<head>
<script type="text/javascript" src="bar.js">
</script>
<!--From what yall say I should have another script
tag here for anything else. Say some variable?-->
<script type="text/javascript">
var a = "hello";
var b = "text";
</script>
</head>
<body>
<!--This should work now?-->
<button type="button" onclick="foo(b,a)">
Click me
</button>
</body>
</html>
bar.js contents:
function foo(id,string){
document.getElementById(id).innerHTML = string;
}
I got this to work.
Thanks everyone.

You need to first include the javascript containing the function:
<script type="text/javascript" src="bar.js"></script>
and then call it in another script tag:
<script type="text/javascript">
foo();
</script>
In your example you seem to have mixed 2 notions into a single script tag which is invalid: include an external javascript file and in the body of the script tag write your code.
According to the specification:
The script may be defined within the contents of the SCRIPT element or
in an external file. If the src attribute is not set, user agents must
interpret the contents of the element as the script. If the src has a
URI value, user agents must ignore the element's contents and retrieve
the script via the URI.
So basically you should avoid such situations and have separate script tags for including external files and for writing inline js.

Related

Why can't I execute JavaScript function inside the <script> tag that defines the .js source?

I am defining the source of a .js file and attempting to call a function from that file in the same tag, as follows:
<script type="text/javascript" src="jsFunctionTest.js">
testMethodCall();
</script>
The .js file just contains:
function testMethodCall(){
window.alert("Hello there");
}
This doesn't work, I don't see the alert.
However, if I change the tag to two tags, as below, then it works:
<script type="text/javascript" src="jsFunctionTest.js"></script>
<script type="text/javascript">
testMethodCall();
</script>
This seems pretty messy. Is there any reason the first one doesn't work?
script elements can have a src attribute or content, but not both. If they have both, the content is ignored (the content is considered "script documentation," not code).
You cannot register an external file and use the content in it, both at a time inside <script> tags. Only either one is allowed.

What does handle_redirect() in JavaScript do?

What will happen if I click a XXX?
It seems I will be redirect to somewhere, but how does it determine where?
Somewhere in your JavaScript code, you should have a function that looks like this :
function handle_redirect() {
...
}
To find your JavaScript code, look for script tags, like this ...
<!-- INLINE JavaScript -->
<script type="text/javascript">
console.log("Inline JavaScript");
</script>
... or like this ...
<!-- an EXTERNAL external JavaScript file -->
<script type="text/javascript" src="assets/js/myscripts.js"></script>
If your handle_redirect function is defined inline, you should be able to find it just by searching for handle_redirect in the code of your webpage.
Usually, however, your JavaScript will be found in external JavaScript files. In that case, you need to search in the code of files that are linked to. So, if you see a script tag with a src eg. equal to assets/js/myscripts.js, just open the file assets/js/myscripts.js with your text editor OR your browser and look for a function that looks like function handle_redirect() { ... } there.

Can an inserted <script> tag be run multiple times without using eval in JavaScript?

I have to use a plugin which bundles js files inside html files (gadgets). For one use case I need to drop and re-instantiate a gadget to run updated code.
So say I have foo.html:
<html>
<head>
<script src="foo.js"></script>
</head>
<body>...</body>
</html>
and foo.js which is the file being injected into my actual document's head:
alert("hello");
Problem is I can only cachebust the html file dynamically and declare my gadget as foo.html?x=123, but the JS file I'm after will still be foo.js so the browser will not re-run it.
Question:
Once a <script> tag is inserted into the document and run, is there any way to run it again without using a module-loader or eval?
Thanks!
You could wrap your code in your <script> tags in a function then call your function. This will allow you to call your code to be called multiple times. Like this:
<script>
function loaded(){
// JavaScript here
}
loaded();
</script>
</body>

Understanding javascript autoexec function triggers

Given an external javascript file with autoexec function syntax:
// external-script.js
(function() {
console.log('external script called');
}());
With the following <script> tag, the external script doesn't execute:
<body>
// ...
<script src="external-script.js" type="text/javascript" />
</body>
But if I add an empty <script> block, as shown below, then the external script executes automatically.
<body>
// ...
<script src="external-script.js" type="text/javascript" />
<script>
// empty
</script>
</body>
Why does the addition of the empty <script> block trigger the autoexecute?
"self-closing" script tags using /> are not valid HTML syntax. Instead, you must always use <script></script>.
<script src="external-script.js" type="text/javascript"></script>
What is happening in your second example is that you are creating a single script tag with <script>//empty as its contents but this gets ignored since it will run the code from the src attribute.
In fact, HTML parsers just ignore all the / inside open-tags. Instead, some tags are always considered to be void elements with no contents (so <img> doesnt need a matching </img>.
For more info see Are (non-void) self-closing tags valid in HTML5?. Keep in mind that HTML5 is basically just a standard that documented the zany behavior that HTML parsers had already been doing all along.

Uncaught ReferenceError $ is not defined

I'm very new to JavaScript (just started a few hours ago and trying to get a script working). I went through a few tutorials on W3 and the 'hello world' code works when I paste it directly into my HTML but I'm having a problem with a script (I've had problems with other scripts as well but I am not sure what I'm doing wrong).
I have this code that I want to test in my HTML, I copied the HTML in and it looks the same then I made a file in my static folder called edit.js and copied the JavaScript into it (exactly as shown). It didn't work no errors on the page but when I click it nothing happens. I tried to paste a W3 'hello world' code in and that worked but this script does not.
I tried to inspect the code in Chrome and that's where I see the above error (under the resources tab). I can open the js file using Chrome which makes me think the js file is accessible and pointing correctly but I'm not sure how to get it working. I'm using Jinja2 as my template engine to render the HTML and in my header I have:
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
and in my main template (the one that gets rendered on all pages) I have:
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
edit.js:
(even putting it within the script tag directly on the page I want to use it on doesn't work)
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});​
HTML:
(it's embedded in a larger page)
<head>
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
</head>
... my html code..
<div id="wrapper">
<div id="container">
<div id="storedvalue"><span>Hello</span> [edit]</div>
<div id="altervalue" style="display:none;"><input type="text" name="changevalue" id="changevalue" value="Hello"> [save]</div>
</div>
</div>
I have never been able to successfully run a JavaScript that wasn't on W3 yet. I get the same problem with other scripts even though I see people online saying they work fine for them. Do I need to do anything extra to make this work?
My two questions are:
What am I doing wrong?
Because Javascript seems to just not work when there's a problem, is there a way to get errors or information on what's actually wrong?
I read Uncaught ReferenceError: $ is not defined? and have been trying to figure this out for the last hour and can't see my problem.
First you need to place the jQuery script tag first.
Second, you need to do one of the following things:
Put your code within this function:
$(document).ready(function(){/*CODE HERE*/});
Or like this:
$(function(){
/*CODE HERE*/
});
The DOM needs to be ready before you can use it. Placing your code within anonymous functions that are executed on the ready event of the DOM is how you can do this.
Edit:
$(function(){
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});​
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Script tag for jQuery should come before your custom javascript.
Follow by edit.js
<script type="text/javascript" src="static/edit.js"></script>
Try removing the language attribute..sometimes work for me. It's obsolete now .. i think
You need to include jquery before you can use it.

Categories