passing a variable (id) from html to external js file with functions - javascript

I'm novel with javascript, and I trying to develop a webpage with dynamics graphs using for that canvas, html 5 and javascript. I wouldn't like to mix html "code" with javascript code, so I decided to keep it separated and call from html the javascript functions. The fact is that when I try to pass my canvas Id to javascript function I'm making a mistake and I have no idea how to fix it. This is my html code:
<html>
<head>
<title></title>
<script type="text/javascript" language="javascript" src="Funciones.js">
window.onload = drawRectangulo('myCanvas');
</script>
</head>
<body>
<h1>Canvas Example:</h1>
<canvas id="myCanvas" width="200" height="100"></canvas>
</body>
</html>
And my JavaScript file is like this:
function drawRectangulo(idCanvas)
{
var Canvas = document.getElementById('idCanvas');
var context = Canvas.getContext('2d');
context.fillRect(50,0,10,150);
}
I don't know if the call to drawRectangulo function on javascript file is right, and if I'm passing the canvas's id right: window.onload = drawRectangulo('myCanvas'); ¿How should I pass the Id from the html file to the js function?. Should I use: ('', "",) or should I create a new variable, initiate it with the canvas's id and pass it to the function? Am I processing good the variable id inside JavaScript function?

You need to do this:
window.onload = function () {
drawRectangulo('myCanvas');
}
Your code is calling drawRectangulo as soon as it runs, and assigning the result of the call (which is undefined) to window.onload.
Edit based on Dan's comment: you also need to change this:
document.getElementById('idCanvas');
to this:
document.getElementById(idCanvas);
Edit 2: You also need to separate your imported script from your inline script, like this:
<script type="text/javascript" language="javascript" src="Funciones.js"></script>
<script type="text/javascript">
window.onload = drawRectangulo('myCanvas');
</script>
A single <script> element can either import a script from another file, or define an inline script, or both. (That explains why moving your inline script elsewhere in your HTML made it work.)

I think this
var Canvas = document.getElementById('idCanvas');
should be
var Canvas = document.getElementById(idCanvas);
With those apostrophes there, you're not referencing the parameter.

I think I know why it doesn't work. I have made this change on html and now is working right:
<html>
<head>
<title></title>
<script type="text/javascript" language="javascript" src="Funciones.js"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
window.onload = function (){
drawRectangulo('myCanvas');
}
</script>
<h1>Canvas Example:</h1>
<canvas id="myCanvas" width="200" height="100"></canvas>
</body>
</html>
I took out the window.onload from the header to the body and it worked. Thanks for your help anyway.

Related

Run time compile order

I'm coding in Javascript and I came to an example which I figure was strange.
Example:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,20,0,2*Math.PI);
ctx.stroke();
</script>
</body>
</html>
The above example works and outputs a circle.
However, when I try to copy the exact codes of the script onto a javascript.js file, the circle ceases to exist. Why is that the case?
<!DOCTYPE html>
<html>
<head>
<script src="javascriptFile.js"></script>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
I thought the order of precedence would be that the web browser publishes the html code, and then constructs the DOM which I figure javascript code would run right after the html objects are created. I tried putting a function createShape() inside the canvas and then insert the rest of the codes in function createShape(){} of the javascriptFile.js file but didn't work either.
Would I have to always put the javascript codes in the html body for all canvas objects?
I thought the order of precedence would be that the web browser publishes the html code, and then constructs the DOM which I figure javascript code would run right after the html objects are created.
That is incorrect. Generally, if your JavaScript code appears in the source before the elements it is trying to access (and is not explicitly marked as defered), it will be executed before the browser continues to parse the page.
Embed the script at the bottom of the body and you should be fine:
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="myCanvas"></canvas>
<script src="javascriptFile.js"></script>
</body>
</html>

My external javascript is not executed

I try to override the window.onload event inside an external javascript, but even when putting some basic console.log line outside the window.load function, the code seems to never execute.
Jumping to code here it is :
for index.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Experimentation</title>
<script src="canvasEntry3D.js" type="type/javascript"></script>
</head>
<body>
<canvas id="canvas" height="720" width="1280"></canvas>
</body>
</html>
for canvasEntry3D.js :
console.log("slkdfnsdnflknegs");
window.onload = abcdefg;
function abcdefg() {
console.log("in start");
var canvas = document.getElementById("canvas");
}
To really know if the browser has loaded the correct javascript file, I have already checked the developper console.
And I'm not searching to override two times the window.onlad event, so there's no need to use addEventListeners (and there is also no other javascript code that override the window.onload event)
The only mistake in your code I see is the wrong type attribute within your script tag.
Just change it from
<script src="canvasEntry3D.js" type="type/javascript"></script>
to
<script src="canvasEntry3D.js" type="text/javascript"></script>

How to call a function from javascript file and save the return value as global

Inside an HTML I have a script:
<script src="info.js" type="text/javascript"></script>
Inside info.js there is a function, lets say getInfo(key) which returns info.
How can I call a function located inside info.js from my html, so that I can use this variable inside the whole html document?
w3schools does not explain how to do this
Something like this:
var global; // global var
// js code...
// function
function myFunc(){
global = getInfo(key);
}
This might help you understand what's going on.
Let's say the code below is located inside info.js
function getSomething(){
return "something";
}
Now your HTML might look like this
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="info.js" type="text/javascript"></script>
</head>
<body>
<span id="mySpan"></span>
<script>
var myText = getSomething();
$('#mySpan').text(myText); //this uses jQuery so you'll need to include that
</script>
</body>
</html>
If I got you correctly, that you want to use that info in all your html file, here's my answer. Let me know if it helps or if you meant anything else, I'll think accordingly.
<html>
<head>
<script src="info.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var info = getInfo(key);
$('div.myinfo').html(info);
});
</script>
</head>
<div class="myinfo"></div>
</html>
You have the desired information in a javascript var and you can assign it as value to a input/select element or copy it as html to a div/td/p/h1 etc.
Just use it like this:
var info = getInfo(key);
As long as your calling script follows the method in info.js (and assuming the function is not private) it should be accessible in any script

assign the javascript code by a javascript function

For some reason, I have to assign the javascript code by a javascript function, like the code at below.
<html>
<head>
<script>
window.onload = init();
function init(){
document.getElementsByName('content')[0] = alert('LOL');
}
</script>
<script type="text/javascript" name="content">
</script>
</head>
<body>
</body>
</html>
After page load, the expected result should like following
<html>
<head>
<script type="text/javascript">
alert('LOL');
</script>
</head>
<body>
</body>
</html>
However, the alertbox doesn't display. Is there anyone can help me?
To get you started:
Don't misspell script
Don't misspell elements
There is no name attribute for script elements
onload = foo() will call foo immediately and assign its return value to onload. Get rid of the ()
Browsers (AFAIK) won't respect modifications to existing script elements, only new ones. So use createElement and appendChild
Write this instead:
window.onload = function init(){
document.getElementsByName('content')[0] = 'LOL';
alert('LOL');
}
Just changing the text of the javascript tag won't make it execute, because it is in the client side. I would do it more like this:
window.onload = init();
function init(){
document.getElementsByName('content')[0] = function SomeMethod(){ alert('LOL'); };
SomeMethod();
}

How to dynamically load the different processing instance

I am having Processing.xhtml which has
<html>
<head>
<script language="JavaScript" src="../js/processing-1.0.0.min.js" type="text/javascript"></script>
</head>
<body onload="doIt();">
<div style="clear:both; float:left;">
<canvas id="sketch" data-processing-sources="../js/k12-processing.pde"></canvas>
</div>
<script type="application/javascript">
var pI;
function doIt() {
if (!pI) {
pI = Processing.getInstanceById('sketch');
}
#{script}
}
</script>
</body>
</html>
The variable 'pI', function name, canvasId are dynamic ones.
Now i want to draw some number of shapes dynamically in different canvas positioned in different place in a page Shape.xhtml. In Shape.xhtml i am referring Processing instance like this
<ui:include src="/Processing.xhtml">
<ui:param name="script" value="#{script}"/>
</ui:include>
After including Processing.xhtml my Shapes.xhtml will look like this
<ui:composition>
<ui:define>
<html>
...
<body onload="doIt_1">
<canvas id="sketch_1">
<script>...</script>
</body>
</html>
<html>
...
<body onload="doIt_2">
<canvas id="sketch_2">
<script>...</script>
</body>
</html>
</uI:define>
The onload event in body element is not triggered properly. How to dynamically load all the scripts in a page?
Web Browsers typically only want one html and one body tag in a single page. If you really want to wait until the page has completely loaded you can use the window.onload. For example at the top of your page you can do something like:
my_funcs = [];
window.onload = function() {
for (f in my_funcs) {
f();
}
}
Then after each of your scripts you can do something like:
my_funcs.push(loadFunc);
That guarantees that each of your load functions will get executed when the page finishes loading. However, if you don't really care about the page being fully loaded you could just execute the load function at the end of each script.

Categories

Resources