Calling a Javascript function from a html file - javascript

My javascript and html files named contents.js and page.html:
function sayHello() {
alert("Hello World")
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="contents.js" ></script>
<script>
window.onload = sayHello();
</script>
</body>
</html>
When run the sayHello function isn't being called. In firefox's console it returns the errors:
-SyntaxError: expected expression, got '<' contents.js:1
ReferenceError: sayHello is not defined
Both files are saved in the same folder. And i'm using a node.js express project in eclipse to create the server:
var http = require('http'),
fs = require('fs');
fs.readFile('./page.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8888);
});
Why am I not able to call the 'sayHello' function in the contents.js file from the page.html file?

The code
window.onload = sayHello();
...calls sayHello and assigns its return value to window.onload, exactly the way x = foo() calls foo and assigns its return value to x.
To just assign the function reference, don't call it (remove the ()):
window.onload = sayHello;
Side note: The window load event happens very late in the page load cycle, only after all other resources are loaded, including all images. Most of the time, you want to run your code earlier. If so, just put it in a script tag that you include at the end of the HTML, just before the closing </body> tag.

Executing sayHello() , you arenot returning anystuff so it was not executed. Had sayHello been returning a function it would have invoked that onload.
var sayHello = (function() {
return function {
alert("Hello World")
};
})();
In this situation, one might use sayHello(), as its returning a function.
window.onload = sayHello;
function sayHello() {
alert("Hello World")
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="contents.js"></script>
</body>
</html>

Put it inside the body tag like this.
<body onload="sayHello()"></body>

Related

JavaScript interdependent functions

I have this in my HTML file:
<script src="/file.js"/>
<script>
func_from_file();
main_func(){
alert("some alert");
}
</script>
And this in my file.js:
func_from_file(){
alert("some alert from file");
}
main_func();
So I have this script in HTML file that calls the function from file.js, and also have a script inside file.js that calls function from html file. How to avoid reference error?
P.S. I can't splice the scripts, can't put script from HTML page inside some file.js, and I can't change loading queue. Help me please.
EDIT:
I will try to correct my question.
HTML page:
<head>
<script src="/file.js"/>
<script>
func_from_file();
start(){
main_func(){
alert("some alert");
}
}
</script>
</head>
<body>
<button onclick="start()"/>
</body>
And file.js:
func_from_file(){
alert("some alert from file");
}
main_func();
NOW it's true code. I have forgot half of it.
I think your problem is not that the functions are wrong, but that you're declaring your script tags wrong, try this:
HTML:
<script src="folder/structure/here/file.js"></script>
<script>
func_from_file();
main_func(){
alert("some alert");
}
</script>
JS:
func_from_file(){
alert("some alert from file");
}
$( document ).ready(function() {
main_func();
});
EDIT:
This is what I got now, I think this is what you want?
HTML:
<html>
<head>
<script src="file.js"></script>
<script>
func_from_file();
function main_func(){
alert("some alert");
}
</script>
</head>
<body>
<button onclick="main_func()"/>
</body>
</html>
JS:
function func_from_file(){
alert("some alert from file");
}
main_func();
or if you want to load the page before showing main_func()
function func_from_file(){
alert("some alert from file");
}
$(document).ready(function() {
main_func();
});
You can put the call of main_func() in file.js inside window.onload = function() {}
This way it will call once whole page gets loaded
or put the main_func() call in file.js inside setTimeout function of javascript and put the timeout according to your convenience.

I can't link javascript files as commonjs modules

I have:
test.json - contains the content to be uploaded into the HTML page
test.js - contains the function that sends an Ajax request to the JSON file, parses, compiles with Handelbars Temlate and puts the content into the HTML page (using innerHTTML).
addcontent.js - javascript file which calls the function from the test.js file
index.html - contains the Handlebars Template, Div
where the content will be placed after processing, and a link to the
addcontent.js.
Everything works, if inside index.html there is a link directly to test.js.
Everything works if I wrap the code inside test.js in a function with variables and call this function in the same file.
But if I call this function from addcontent.js and connecting addcontent.js and test.js using commonJS module approach, it does not work.
Probably I made a syntax mistake somewhere, but I don't see it.
P.S. I use NodeJS, NPM, HTTP-server and I'm going to merge all javascript files using browserify after all
//test.js
module.exports = function addContent (jsonDir, templId, finId){
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', jsonDir);
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById(templId).innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById(finId).innerHTML += template(response);
})
}
/* test.json */
{
"time": "03:47:36 PM",
"milliseconds_since_epoch": 1471794456318,
"date": "08-21-2016-123",
"test": "lalala 123"
}
/* addcontent.js */
var addContent = require('./test');
addContent("json/test.json", "date-template", 'testData');
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="handlebars-v4.0.5(2).js"></script>
</head>
<body>
<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b>
</span>
</script>
<script type="text/javascript" src="addcontext.js"></script>
</body>
</html>

Can't call external javascript function from JQuery

I have a script file called trim.js. I'm trying to call a function prepareURL() from this file in my index.html file. However I'm getting the following error:
ReferenceError: Can't find variable: prepareURL
I make sure to import my script doing the following:
<script type="text/javascript" src="./js/trim.js">
</script>
<script type="text/javascript">
$(function() {
$('#simple_sketch').sketch();
$('#simple_sketch').sketch('color','#fff');
$('#simple_sketch').sketch('size','6');
});
function predict() {
//Create Image URL
var imageURL = prepareURL('#simple_sketch')
}
The function in my trim.js file looks like this:
function prepareURL(c) {
//My code
}
How can I call prepareURL from my index.html file?

Google script return from code.gs to index.html

How can I return something from code.gs to index.html.
I have tried this in "Index.html", but this doesn't work.
index.html
$('#test').click(function() {
alert(google.script.run.getAmountOfImages());
});
Code.gs
function getAmountOfImages()
{
return "Tom"
}
Please help.
According to the documentation
"google.script.run is an asynchronous client-side JavaScript API
available in HTML-service pages that can call server-side Apps Script
functions."
therefore your result will be returned in a callback. So you will have to use Handler functions i.e withFailureHandler and withSuccessHandler
google.script.run
.withFailureHandler(function(err){
console.error("error occured", e);
})
.withSuccessHandler(function(res){
alert(res);
})
.getAmountOfImages();
res Parameter in success handler callback function will hold the response from google app script.
google.script.run is what you need.
See the example below.
code.gs
function runOnGsAndGetValue() {
return "Hello World!";
}
function runOnGsOnly() {
Logger.log("Hello World"); // On Appscript go to 'View' -> 'Logs' to see your Logs
}
sample.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="para">Hello World</p>
<br>
<button onclick="onlyRun()">Run Code in Code.gs Only</button>
<br><br>
<button onclick="runAndGet()">Run Code in Code.gs and Return a Value</button>
<script>
function setText(text){
var div = document.getElementById('para');
div.innerHTML = text;
}
function onSuccess(str) {
setText(str);
}
function onFailure(error) {
setText("ERROR: " + error.message);
}
function runAndGet(){
google.script.run.withFailureHandler(onFailure).withSuccessHandler(onSuccess).runOnGsAndGetValue();
}
function onlyRun(){
google.script.run.runOnGsOnly();
}
</script>
</body>
</html>

Phonegap - How to call one javascript function in another file from index page?

I am an iOS and PhoneGap newbie. I have the index.html file and a javascript file called MyClass.js.
In my MyClass.js, I have a function -
var MyClass = {
testfunc: function() {
navigator.notification.alert("Success : \r\n");
}
}
I am trying to call it from the index.html function like -
MyClass.testfunc();
In my Phonegap.plist file I have an entry MyClass-Myclass as a key-value pair with the type String. However I don't get the alert. What am I doing wrong?
Have you included the following in your index.html:
<script src="MyClass.js"></script>
This will allow you to use the MyClass.js functions in your index.html file
Your markup for your alert is wrong...
navigator.notification.alert(
'Some Alert Text here', // alert message
successCallback, // callback function
'Alert Title, // alert title
'OK' // button text
);
Hi can you try following code:
// MyClass.js
var MyClass = {
testFunction: function() {
alert("hi there");
}
};
// index.html
<html>
<head>
</head>
<body>
<script src="MyClass.js"></script>
<script src="phonegap-1.3.0.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", function() {
navigator.notification.alert("hi there \r\n");
//alert("hi there \r\n");
});
</script>
</body>
</html>

Categories