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
Related
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
How can I get my extension to work on all frames like adblock does?
I tried adding "all_frames" : true to my manifest file but it didn't work.
I tried to use this code to get the text with specific ids:
var theId = "starts with something";
var myArray = [];
$('[id^="theId"]').each(function(i, obj) {
myArray.push($(this).text());
});
$.unique(myArray);
console.log(myArray);
but it says my array is empty. When I inspect element on the page, I see a "top" layer, and a "target content" layer. The code only works when I execute it in the console on the "target content" layer. Can I use this code in a content script, or do I need to use background.js somehow?
Continued from SO44122853
I see you figured out that the content was loaded in an iframe. So I have a working demo here PLUNKER, the snippet is here just in case the plunker goes down.
Details are commented in PLUNKER
Demo
Not functional due to the need to run 2 separate pages
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<style></style>
</head>
<body>
<!--iframe is same as the one on the site, with the exception
of the src-->
<iframe id="ptifrmtgtframe" name="TargetContent" title="Main Content" frameborder="0" scrolling="auto" width='90%' src="tables.html"></iframe>
<!--The data is displayed as a one string-->
<output id='display'></output>
<script>
// Reference the iframe
var iFID = document.getElementById("ptifrmtgtframe");
// Register the load event on iframe
iFID.onload = function(e) {
// Callback is extractText function
return extractText('#ptifrmtgtframe', '#display', '.PSLONGEDITBOX');
}
/* Pass iframe and display as a single selector
|| Pass targets as a multiple selector
*/
function extractText(iframe, display, targets) {
var iArray = [];
var iFrame = document.querySelector(iframe);
var iView = document.querySelector(display);
var iNode = "";
/* .contentWindow is property that refers to content
|| that is in an iframe. This is the heart of the
|| demo.
*/
var iContent = iFrame.contentDocument || iFrame.contentWindow.document;
var iTarget = iContent.querySelectorAll(targets);
/* .map() will call a function on each element
|| and return a new array as well.
*/
Array.from(iTarget).map(function(node, idx) {
iNode = node.textContent;
iView.textContent += iNode;
iArray.push(iNode);
return iArray;
});
console.log(iArray);
}
</script>
</body>
I think your script may be executing before the DOM loads, try putting your function inside:
document.addEventListener('DOMContentLoaded', function() {
});
EDIT
That event seems to do nothing in content scripts, I think that is because they are already loading after DOM is loaded, and never fires.
However this seems to fire but not sure why:
$(function(){
//something
});
This needs jQuery injected aswell
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>
...
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>
I'm not quite sure what goes on between <script> tags. For example, the following gives a reference error and type error in Chrome:
<html>
<head>
<script type="text/javascript">
T.prototype.test = function() {
document.write("a");
}
</script>
<script type="text/javascript">
function T() {}
var v = new T();
v.test();
</script>
</head>
<body>
</body>
</html>
But this works:
<html>
<head>
<script type="text/javascript">
</script>
<script type="text/javascript">
T.prototype.test = function() {
document.write("a");
}
function T() {}
var v = new T();
v.test();
</script>
</head>
<body>
</body>
</html>
The upper script is executed first in the first example, so it doesn't know about T yet, hence the error.
In the second example, T is well defined and known anywhere as soon as the script tag is executed. This is due to function declarations being hoisted to the top, no matter what the order is, they are always available. Function declaration hoisting is more deeply explained here
The second example after hoisting is applied:
var v,
T = function(){}; /* using comma like this is short-hand for: var v; var T = function(){}; */
T.prototype.test = function() {
document.write("a");
};
v = new T();
v.test();
They are each parsed in the global context, but in order. The entire first script tag is parsed and executed before the second one is considered. As part of parsing a script, function declarations are recognized ahead of time, which is why the second one works while the first one doesn't.