How to use an external javascript function in html - javascript

I'm currently trying to build a webpage using html and an external javascript file. The javascript file is named "main.js" and is in the same directory as the html file. I'd like to call a function from the javascript file inside the html file.
The function is linked to a button as is called using the following line:
<button onclick="myFunc()">Click Me</button>
If I use the script tag and embed the javascript inside the html file it works fine, with format:
<script>
funtion myFunc(){
//Code here
}
</script>
When I put this function in a separate main.js file and then call it using
<script type="text/javascript" src="/main.js"></script>
the button does nothing. Is there a syntax I'm missing?
ADDITION edit:
Here's and edit to hopefully make the question more clear. I am a beginner in javascript so apologies if I'm asking in an unclear way. Below is the full javascript function I'm using to test in my html file. It's from w3 schools and I'm just using it to test. The function moves a square from the top left of a larger square to the bottom right.
<script>
function myMove() {
var id = null;
var elem = document.getElementById('myAnimation');
var pos = 350;
clearInterval(id);
id = setInterval(frame,10);
function frame() {
if (pos == 0){
clearInterval(id);
} else {
pos--;
elem.style.bottom = pos +'px';
elem.style.right = pos + 'px';
}
}
}
</script>
When directly embedded in the html code, it works just fine. When I put this exact function in an external javascript file, named 'test.js', and then include the reference to that file in the html, so the body of the html file is:
<script type="module" src="/test.js"></script>
<button1>home</button1><br>
<button onclick="myMove()">Click Me</button>
<div id ="myContainer">
<div id ="myAnimation"></div>
</div>
For reference, the javascript file looks like this:
import './style.css'
function myMove() {
var id = null;
var elem = document.getElementById('myAnimation');
var pos = 350;
clearInterval(id);
id = setInterval(frame,10);
function frame() {
if (pos == 0){
clearInterval(id);
} else {
pos--;
elem.style.bottom = pos +'px';
elem.style.right = pos + 'px';
}
}
}
Nothing happens. Does this make the question more clear?

I did this and it worked for me(the files are separate)
function myFunc() {
alert("hello")
}
<html>
<head>
</head>
<body>
<h1> Testing... </h1>
<button onclick="myFunc()"> Click Me </button>
<script src="./main.js"></script>
</body>
</html>
Its also a good idea to be running your code in a simple python server.
Python Simple Server Setup

Related

How to call a function in external script file from HTML

I'm trying to call a javascript function in my HTML index file and I can't get it to work.
This is my html file that I'm trying to call a function from.
<div class="main">
<h1 class="header-main" onload="HeaderTyper('Welcome', this)">
<noscript>no javascript</noscript>
</h1>
</div>
<script type="text/javascript" src="script.js"></script>
And this is the script.
function HeaderTyper(message, element){
var i = 0;
var speed = 50;
if (i < message.length) {
element.innerHTML += message.charAt(i);
//play keystroke sound
i++;
setTimeout(HeaderTyper, speed);
}
}
I'm trying to get a typewriter effect style header. I'm planning to add some keystroke sounds, but first I need to figure out how to actually type it out in the header tag. The code won't type out the message I'm passing in argument. What did I do wrong ? Thank you for any help.
After the HTML page ends (As #johannchopin explained), import the file and then add an event listener (as #aaronburrows explained).
<body>
<div class="main">
<h1 class="header-main">
<noscript>no javascript</noscript>
</h1>
</div>
</body>
</html>
<script type="text/javascript" src="script.js"></script>
<script>
let h1 = document.querySelector('.header-main');
h1.addEventListener('load', HeaderTyper("Welcome", h1, false));
</script>
Also, I fixed the function, it was missing the parameters.
function HeaderTyper(message, element, i) {
var speed = 50;
if (i < message.length) {
console.log(message.charAt(i))
element.innerHTML += message.charAt(i);
//play keystroke sound
setTimeout(function(){ HeaderTyper(message,element,++i)}, speed);
}
}
You're attempting to bind a function call before it is loaded into the browser. Remove the onload from the HTML and add an event listener to the script.
According to this solution, The onload event can only be used on the document(body) itself. Best way to achieve this is to call the function in a <script> tag just before the </body> closing tag:
<div class="main">
<h1 class="header-main">
<noscript>no javascript</noscript>
</h1>
</div>
<script>
function HeaderTyper(message) {
var i = 0;
var speed = 50;
var element = document.querySelector('.header-main');
if (i < message.length) {
element.innerHTML += message.charAt(i);
//play keystroke sound
i++;
setTimeout(HeaderTyper, speed);
}
}
HeaderTyper('Welcome');
</script>
Ok, hi there.
function HeaderTyper(message, element){
alert('script loaded') //<---
var i = 0;
I put this line at the beginning of the script to make sure it works. And it's not.
Why?
Because you just made your function but doesn't call it.
First way to solve this - put ur function in the "script" of HTML doc. And call it after, like
<script>
function HeaderTyper(message) {
let i = 0
let speed = 50
let element = document.querySelector('.header-main')
if (i < message.length) {
element.innerHTML += message.charAt(i)
i += 1
setTimeout(HeaderTyper, speed)
}
}
HeaderTyper('Welcome') //<---
</script>
Second way - put HeaderTyper() at the end of script.js file, so the function start, but you need to make a link for "message" and "element".
setTimeout(HeaderTyper, speed);
}
}
HeaderTyper(someMessage, someElement) //<---

Problem with local progress bar code while it works properly on CodePen? [duplicate]

I'm trying to run a simple few lines of code using an index.html file and a script.js file, nothing else.
In the HTML file, I have doctype html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/script.js"></script>
</head>
<body>
<div id="content1">This is content 1 </div>
<div id="content2">This is content 2 </div>
<div id="content3">This is content 3 </div>
</body>
</html>
And for my javascript section i have:
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
}
}
When I run this in CodePen, or even on the code editor on this website, it works fine. But it doesn't work when I use the files on my desktop (index.html, script.js I do believe the folder structure is correct (script.js is in the javascript folder.)
Thank you all
Move your script tag just before the closing of the body tag:
<script src="javascript/script.js"></script>
</body>
This way the DOM will be available when your script runs.
If you prefer to keep your script in the head part, then wrap your code in a DOMContentLoaded event handler:
document.addEventListener("DOMContentLoaded", function() {
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
}
}
});
... so to have your code run when the DOM is ready.
You did not tag your question with jquery, but as you seem to use it, you can use this shorter code for doing essentially the same as above:
$(function() {
var $elems = $("div").hide(),
$elems.eq(Math.floor(Math.random() * $elems.length)).show();
});
wrap your code in this function to execute it if the document is ready.
$(document).ready(function (){
// your code goes here
});

Can't call function from body onload (uncaught reference error: start is not defined) javascript

I have a body onload calling a function in javascript. I Have tried many things, but the console just prints to the error log: uncaught reference error: start is not defined. I think it might be a malfunction, please notify me if it works for you. My code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Monster Invasion</title>
<script type="javascript">
var hur;
var monsters = 10;
var objective = false;
var health = 100;
var damage = 30;
var sheild = false;
var ea = 1;
function start() {
setTimeout(hurt,4000)
}
function hurt() {
var newhelth = health - damage;
health = newhelth;
document.getElementById("healtw").innerHTML = health;
start();
}
function kill() {
if(monsters > 0) {
monsters--;
document.getElementById("monster1").src="dead.jpg"
setTimeout(next,2000)
}else {
objective = true;
document.location="endoflevel.html";
}
}
function next() {
document.getElementById("monster1").src="monster.jpg"
}
}
</script>
</head>
<body onload="start()">
<p id="healtw"></p>
<embed src="guide_first_level.mp3" type="audio/mp3" hidden="true" autostart="true">
<a id="st" onclick="kill()"><img id="monster1" src="monster.jpg"></a>
<p id="ada"></p>
Activate sheild
</body>
</html>
your script type is wrong.
try like this
<script type="text/javascript">
</script>
However, you don't need to mention script type. just use a plain script tag.
like this
<script>
</script>
One more thing to add that before the end of the script tag, you gave an extra }.
just remove it
function next() {
document.getElementById("monster1").src="monster.jpg"
}
} // <-- just remove this bracket
</script>
Well for some of you, who are using external js file, please just check to see whether you linked your file or not :)... because I had the same error but as I looked through my code ..I hadn't linked the file then!
just in case you came here looking for an answer too!
There are two problems with your code.
javascript is not a valid type for the script in the browser. Browsers know text/javascript, but not just javascript, that is why your code is not being executed. Change the type attribute or remove it at all (for text/javascript is the default value).
You have an extra bracket } at the end of the code. Remove it and your code will work fine.
There are 3 errors:
Correct the type of your script tag
There is an extra } at the end of your code
Instead of using onload() for body tag, you should better use window.onload as follows in order to make sure your start() function is run once document is ready:
...
<head>
<title>Monster Invasion</title>
<script type="text/javascript">
window.onload = function(){
// Put all your code here
// And at the end run start() function
start();
}
</script>
</head>
<body>
...

Calling function from external JS

I am trying to call a function from an external .js file but the console is returning errors and the function is not being called. How do I correct my code and be able to call the function properly.
Here is the main .html file:
<html>
<head>
<script type="text/javascript" src="xp.js">
</script>
<script type="text/javascript">
window.onload = xyz.makeShape.Circle();
</script>
</head>
<body>
<canvas id="xyz" width="600" height="600"></canvas>
</body>
</html>
And here is the .js file:
var xyz = xyz || {};
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
xyz.makeShape = {
Circle : function() {
console.log('working');
}
}
EDIT
I am getting 2 errors in the console:
Error 1
TypeError: canvas is null
window.onload = xyz.makeShape.Circle;
Error 2
TypeError: xyz.makeShape is undefined
window.onload = xyz.makeShape.Circle;
Change this:
window.onload = xyz.makeShape.Circle();
to this:
window.onload = xyz.makeShape.Circle;
window.onload needs to be set to a function reference, not to the results of calling a function.
You also can't do these two lines from the <head> section before the DOM is loaded:
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
You need to execute those after the DOM has been loaded. There are multiple possible strategies for doing that. The easiest for what you already have would be to execute them in your onload handler since you know the DOM is already loaded there. You could also move the script tag that loads your external .js file to the end of the <body> section and the DOM will already be ready then when that js file runs.
You will just need to include the js file using the <script> tags - either in your header or footer.
<script type="text/javascript" src="js/yourjsfile.js"></script>
Now you can call functions from that script as if they were in the current file
Edit
If you're sure that the file is already included (first make sure you've got the path right) next you need to check your console from errors that may be arising from the included file. The code you've supplied looks right.
External js:
var xyz = xyz || {};
xyz.makeShape = {
Circle: function () {
console.log('working');
}
}
Internal js:
window.onload = function () {
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
xyz.makeShape.Circle();
}
Tested and works

How to run and display processing code (currently in part of the document.body) in an html canvas?

NOTE: I know I can import .pde files but I need to run code on screen so I will not be using this.
My three following attempts failed. I do not know which one was closer to achieving and I do not prefer one as long as it produces desired result. Appreciate the help by helping me get any of the attempts working/suggesting a new one.
1ST ATTEMPT) - use getText function written below but then some text that is not code can be found in the resulting jscode variable and thus the processing instance does not work.
function getText(n) {
var s = [];
function getStrings(n, s) {
var m;
if (n.nodeType == 3) { // TEXT_NODE
s.push(n.data);
}
else if (n.nodeType == 1) { // ELEMENT_NODE
for (m = n.firstChild; null != m; m = m.nextSibling) {
getStrings(m, s);
}
}
}
getStrings(n, s);
var result = s.join(" ");
return result;
}
var processingCode = getText(document.body)
processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = document.getElementById("mysketch");
var processingInstance = new Processing(canvas, jsCode);
....
<span class="sketch">
<canvas id="mysketch"></canvas>
</span>
2ND ATTEMPT) Same as above but added a tag with id="all_processing_code" but couldn't figure out how to get the text within anyway. This did not work:
var processingCode = getText(document.getElementbyId(all_processing_code));
3RD ATTEMPT) Removed getText and tried to use JQuery text() to isolate the code. Was having trouble mixing JS and Jquery though. Tried different stuff and none worked. What would be appropriate way to mix it in? What script type should I use? This was confusing.
<script type="text/jquery">
var processingCode = $('#all_processing_code').text();
//processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = $.Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = $(#'mysketch');
var processingInstance = new $.Processing($('canvas'), $('jsCode'));
}
</script>
First, check if your processing code is wrapped by an html element (like a div or something else) with an id. If it isn't, please do it!
For exemple:
<div id="mycode">
void setup() {
background(0);
}
</div>
After this, check if you have the getProcessingSketchId() function declared in your code. Processing IDE in JavaScript mode already exports html files with that function. If there isn't, please declare it inside your <head>:
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
You can include JQuery from google api including this line in your html before you use JQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
Assuming that you want to run your processing code when the page just has loaded, just append this code after the getProcessingSketchId() declaration.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
You can create this code inside any other <script type="text/javascript">.
At the end, you will have something like this:
<html>
<head>
<!-- Your title, meta tags, stylesheet and all other stuff here -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
</head>
<body>
<div id="mycode">
void setup() {
background(0);
}
</div>
</body>
</html>

Categories

Resources