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?
Related
I have a header.html and header.js files because I want to use the same header through my webpages.
In header.js file, on window load I want it to console.log("header file loaded").
I also have index.html and index.js file for my homepage. In index.js, on window load I want it to console.log("index file loaded")
I called header.html in index.html file, in order to import the header for the homepage. This works fine.
based on js files the console output should
header file loaded
index file loaded
The problem I am having is that
it seems like header.js and index.js cannot work simultaneously
only the last referenced file gets outputed in the console
for example this format
<script src="js/header.js"></script>
<script src="js/index.js"></script>
will output
index file loaded
and this
<script src="js/index.js"></script>
<script src="js/header.js"></script>
will output
header file loaded
I use the code to import header.html in index.html
<head>
<div data-include="header"></div>
</head>
<body>
<script>
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var file = $(this).data('include') + '.html';
$(this).load(file);
});
});
</script>
</body>
this is the content of both js file
function retrieveInfo(data) {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/Sellers/' + userId).once('value').then(function(snapshot) {
console.log(userId)
console.log("index file loaded")
});
}
})
}
what am I doing wrong and how can I fix it to have both js file called?
You are doing it in a wrong way, .load() is used for loading HTML contents. You should be using .getScript(), to load the js and execute it.
According to docs:
.load()
Load data from the server and place the returned HTML into the matched element.
.getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.
Here is an example for using getScript:
$.ajax({
url: url,
dataType: "script",
success: function() {
alert("script loaded");
}
});
In your case it would be:
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var JS = $(this).data('include') + '.js';
var file = $(this).data('include') + '.html';
$(this).load(file);
$.ajax({
url: JS,
dataType: "script",
success: function() {
alert(file + " loaded");
}
});
});
});
Please help,
My javascript code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function() {
var url = "../Account/DeconnecterUtilisateur";
var statutLogin = #HttpContext.Current.User.Identity.Name;
$.getJSON(url, { usr: id }, function (data) {
console.log(data);
})
});
</script>
is throwing this error message
(index):87 Uncaught ReferenceError: patrice is not defined
And I can not get arround it.
My aim is to call within my account controller a method that will log off the user when ever that specifc view(that cobtains the script) is loaded.
Rewrite to this:
var statutLogin = '#HttpContext.Current.User.Identity.Name';
Notice you need the apostrophes above since c# is generating js code before the script runs.
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>
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>
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>