Calling function from external .js file, nothing happens - javascript

I have a really basic JavaScript project, I'm just testing out and learning the language. All I want the program to do is launch and call a function inside the external main.js file. At the moment nothing happens on launch.
I have tried copying examples given online but they don't seem to be working for me.
HTML File:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Cex_Program</title>
<link href="css/default.css" rel="stylesheet" />
</head>
<body>
<div>Content goes here!</div>
<script src="js/main.js"></script>
<script>
Main();
</script>
</body>
</html>
JavaScript file:
Content of function is irrelevant, I just want the program flow to enter the function (hit my breakpoint);
// Your code here!
var InfiniteLoop = 1;
var DeltaTime = 0;
function Main()
{
var Day = new Date();
var StartTime = Math.round(new Date() / 1000);
var StartCurrentLoopTime = 0;
var EndCurrentLoopTime = 0;
}

This does work
<!DOCTYPE html>
<html>
<body>
<div>Content goes here!</div>
<script>function Main( str ) { console.log( str ); }</script>
<script>
Main( "Main!" );
</script>
</body>
</html>
So
We can deduce from this that either js/main.js is not being downloaded, the function Main() is inaccessible to a <script> outside it or that Main() simply doesn't function or produce a discernable result.
See this w3schools tutorial about scopes for more details on why Main() might be inaccessible.
Check your browser's console for errors in the case of Main() not functioning.
FireFox: https://developer.mozilla.org/en/docs/Tools/Browser_Console
Chrome: https://developers.google.com/web/tools/chrome-devtools/console/
I will happily update this answer as needed in response to positive feedback.
To test if Main() is accessible
Check if Main() is a global function by finding out if window.hasOwnProperty( "Main" ) before typing to use it.
<!DOCTYPE html>
<html>
<body>
<div>Content goes here!</div>
<script>
( function() {
function Main( str ) { console.log( str ); }
} () );
function Alt( str ) { console.log( str ); }
</script>
<script>
if ( window.hasOwnProperty( "Main" ) ) {
Main( "Main!" );
} else {
console.error( "Main() can't be accessed from here" );
if ( window.hasOwnProperty( "Alt" ) ) {
Alt( "Alt!" );
}
}
</script>
</body>
</html>

I created your setup on my dev machine and loaded the html page. Assuming the files are named correctly on your machine, I can confirm that the code did execute.
A good way to check if JavaScript is running correctly in the browser is to use a debugger:
Google Chrome
Mozilla Firefox
Microsoft Edge/IE
Apple Safari

Related

Emscripten triggers spurious function calls

I'm trying to get myself used to emscripten, and I have to admit that my JS is quite rusty. Anyway, as a start, I tried to compile
#include <vector>
extern "C" {
int add(int a, int b){
return a+b;
}
}
with emscripten: em++ test.cpp -sEXPORTED_FUNCTIONS=_add -sEXPORTED_RUNTIME_METHODS=ccall,cwrap. I wrote the following basic HTML page:
<!DOCTYPE html>
<html>
<head>
<script src="a.out.js"></script>
<script>
function run(){
alert("Run!");
var add = cwrap("add", "number", ["number"]);
var result = add(12, 13);
document.getElementById('output').value = result;
}
</script>
</head>
<body>
<button onclick="run();">Run!</button>
<input id="output">
</body>
</html>
The strange thing is than run() is called immediately on loading the page, which firefox unsurprisingly does not like:
Uncaught (in promise) RuntimeError: Aborted(Assertion failed: native function `add` called before runtime initialization)
and is not intended anyway. If I remove the line
<script src="a.out.js"></script>,
then the spurious call to run() disappears. Of course, this renders the page dysfunctional.
How to do it properly?
I am using Firefox 107.0.1 (MacOS) and em++ 3.1.28-git from Homebrew.
Emscripten creates hundreds of variable and function into the global namespace by default, and run is one of them.
MODULARIZE prevents namespace polution.
em++ test.cpp -sEXPORTED_FUNCTIONS=_add -sEXPORTED_RUNTIME_METHODS=ccall,cwrap -sMODULARIZE -s 'EXPORT_NAME="createModule"'
And use that module.
<!DOCTYPE html>
<html>
<head>
<script src="a.out.js"></script>
<script>
var module = null;
var add = null;
createModule().then(m => {
module = m;
add = module.cwrap("add", "number", ["number"]);
});
function run(){
alert("Run!");
var result = add(12, 13);
document.getElementById('output').value = result;
}
</script>
</head>
<body>
<button onclick="run();">Run!</button>
<input id="output">
</body>
</html>

Redirect to differnent URL and load a javascript file

I am working on a project - When the URL to my site (www.mywebsite.com), is entered, I want it to go automatically go to a different website in the same browser window and then go another website (www.anotherWebsiteOne.com) in the same and the after X seconds will load another webSite (www.anotherWebSiteTwo.com) in the same browser, and so on.
I would like everytthing to stay in the same browser window
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Basic Javascript Example</title>
<script type="text/javascript" src="webSites.js"></script>
</head>
<body onload="start()">
</body>
</html>
and my webSites.js:
var webSites = [
'http://www.anotherWebPageOne.com/',
'https://www.anotherWebPageTwo.com/',
'http:www.anotherWebPageThree.com/',
];
var iTarget;
function nextTarget(){
window.open( targets[iTarget], 'target' );
if( ++iTarget >= targets.length ) {
iTarget = 0;
}
}
function start() {
iTarget = 0;
nextTarget();
setInterval( nextTarget, 5000 );
}
start()
you can use :
<body onload="start()">
</body>
or you can simply add start() to the end of your js file
just add start() to end of your webSites.js file
whatever in your js file will be executed automatically and you have to just call the start function in the js file by invoking it.
also, rename your webSites variable to targets.
in your JS file you just need to add window.onload = <Your Function Name>;
eg:-
var webSites = [
'http://www.anotherWebPageOne.com/',
'https://www.anotherWebPageTwo.com/',
'http:www.anotherWebPageThree.com/',
];
var iTarget;
function nextTarget(){
window.open( targets[iTarget], 'target' );
if( ++iTarget >= targets.length ) {
iTarget = 0;
}
}
window.onload = nextTarget;
function start() {
iTarget = 0;
nextTarget();
setInterval( nextTarget, 5000 );
}
I hope it will solve your problem

Why is dom.innertext was updated and rendered after the while is finished in this example?

I am pretty new to javascript and am working on an assignment.
The problem I have can be demonstrated via codes below:
For HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A3Q5</title>
<script src='xxx.js'> // external js
</script>
</head>
<body>
<div class="container">
<button id="startBtn">Start</button>
<div id="displayStart">x</div>
</div>
</body>
</html>
For the xxx.js code:
function setup(){
document.getElementById("startBtn").addEventListener('click',startRace,false);
}
function startRace(){
var test = document.getElementById("displayStart");
test.textContent = "adsasdasds";
console.log(test.textContent);
var c = 5;
while(c--){
var counter = 500000000;
while(counter--){} // try to simulate some delays
}
}
window.addEventListener('load',setup,false);
so the problem is, when I run the program and click the button, the console prints "adsasdasds" however the div element is not updated in the browser until the first while loop is done....
Doesn't js run sequentially like java / C++ if no async is specified ?
Hope someone can help me out
The desired result will be : the div is updated before entering the while loop as the sequence of code execution...
Thank you !

not able to load contents in div using javascript

this is shan and i'm a javascript noob and i'm trying to work qa code as an example here. i'm trying to load a small javascript content to a div element but it is not working any help would be great and here is the code.
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext () {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerhtml="adding 1 to 100 gives "+sum;
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
You need to call the function. It's also a good idea to wait until the window is loaded (or you can use some more advanced JS to detect the DOM ready state.):
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext() {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML = "adding 1 to 100 gives "+sum;
}
window.onload = function(){
displaytext();
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
3 problems:
You never actually call the function. It is only declared.
The property is innerHTML not innerhtml. Javascript is case-sensitive.
The script is above an element is is referencing. As scripts are executed as they are found (page construction is paused during execution) the element you are referring to is never found.
Also you declare the loopindex variable twice, which i think will cause a syntax error on ES5 strict.
<html>
<head>
<title>
using d for statement
</title>
</head>
<body>
<div id="targetdiv">
</div>
</body>
<script>
function displaytext () {
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML="adding 1 to 100 gives "+sum;
}
displaytext();
</script>
</html>

javascript error with label

I have a function as follows:
function textNext(element, num) {
document.getElementById("lblContent").innerHTML = "hello";
}
However, the text of the lblContent label won't change when the function is called.
What am I doing wrong?
btw : lblContent is of type asp:Label
Since lblControl is a server side ASP.NET control, you will need to use the control ClientID property in order to use it in javascript:
function textNext(element, num) {
document.getElementById(<"%=lblContent.ClientID%>").innerHTML = "hello";
}
Check the console in your browser for errors. I tried to reproduce your problem in a standard HTML/Javascript environment.
This works for me.
<html>
<head>
<title>Test</title>
<head>
<body>
<div id="lblContent">Previous text</div>
Change text
<script type="text/javascript">
function textNext() {
document.getElementById("lblContent").innerHTML = "Next text";
}
</script>
</body>
</html>

Categories