In html5 how do i place the class below (constructor and method)in another file and reference it in the html file.
Below I have everything in 1 file and I dont want that.
<canvas id="myCanvas" width="600" height="400"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.font="14px Arial";
//how to move to other file
function ClassPerson(gender,name1) {
var aa;
this.gender=gender;
this.name1=name1;
aa=6;
};
//how to move to other file
ClassPerson.prototype.m_sayGender = function()
{
ctx.fillText("this gender= " + this.gender + " gender=" + this.name1,10,40);
};
//stay in this file
var person1 = new ClassPerson('male','dave');
var person2 = new ClassPerson('female','bet');
ctx.fillText("this gender= " + person1.gender,10,20);
person1.m_sayGender();
myObject._three();
</script>
You simply create an external JS file with your code
and include it like this:
<script src="myFile.js"> </script>
or
<script src="<myFile>.js" type="text/javascript"></script>
Be sure to place the JS file in the directory where you have your HTML file
After comment: I guess you have to dynamically create an image with javacript set it's src porpertie and the diplay it.
Set the whole JS code of your class in an external *.js file. Then import it into your *.html file like this:
<script src="<external-file-name>.js" type="text/javascript"></script>
Related
Is this possible, and if so how is it done?
I do not want to use iframes.
I want to write the html of just a div in a separate file. I want to then insert this into my body of my html.
I then want to write a separate js file which operates the code in the div.
So my html file would look like this:
mydivhtml.html (It is just this html, no headers or body etc)
<div id="mydivhtml" style="width: 30vw; height: 100vh;">
<button id="myButton" onclick="MyOnClick();"></button>
<label id="myLabel"></label>
</div>
My js file would be a normal js file:
mydivjs.js
function MyOnClick(){
document.getElementById("myLabel").innerHTML = "Hello";
}
Then when I wanted to use this, I include the js file as normal:
<script type="text/javascript" src="mydivjs.js"></script>
But, then I just add the html in some way.
I know people advise not to do document.body.innerHTML = document.body.innerHTML + "<div>Hello!</div>"; because it will keep on firing onload.
So I want to do something like this:
var myDiv = document.createElement("div");
myDiv.id = 'mydivhtml';
myDiv.innerHTML = "<button id=\"myButton\" onclick=\"MyOnClick();\"></button>"
"<label id=\"myLabel\"></label>";
document.body.appendChild(myDiv);
BUT how do you do this from just the mydivhtml.html without having to write it out bit by bit?
So if your directories is like this
Main -|
|main.html
|mydivhtml.html
|mydivjs.js
then you should have this code on your main.html
<script>
fetch("./mydivhtml.html").then(x=>x.text()).then(data =>{
var myDiv = document.createElement("div");
myDiv.id = 'mydivhtml';
myDiv.innerHTML = data;
document.body.appendChild(myDiv);
// need to have mydivjs.js as a script
var mydivjs = document.createElement("script")
mydivjs.src ="./mydivjs.js"
myDiv.appendChild(mydivjs)
})
</script>
hope it works...
My script works when it is included in the html file, but when I move it to an external .js file, canvas doesn't draw.
this is my html file:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<title>Reveal RGB Values</title>
<form action='/' method='POST' enctype='multipart/form-data'>
<h1>Select file to upload:</h1>
<br>
<input type='file' name='file'>
<input type='submit' value='submit'>
</form>
{% if status == 'uploaded'%}
<h1>There will be a photo here</h1>
<canvas id="frame"></canvas>
<canvas id= "solution_frame"></canvas>
<div id="solution"></div>
{% endif %}
<script type = text/javascript src="{{ url_for('static', filename='script.js') }}"></script>
</body>
In the external .js file, I have two canvases that successfully get built (I can see empty blanks that match the sizes)
var frame = document.getElementById('frame');
frame.width = 800;
frame.height = 600;
var context = frame.getContext('2d');
var solution_frame = document.getElementById('solution_frame');
var solution_context = solution_frame.getContext('2d');
solution_frame.width = 25;
solution_frame.height = 25;
but I cannot draw the image
function draw_image(){
base_image = new Image();
// yay! jinja works here too.
var image_url = '{{img_url}}';
base_image.src = image_url;
base_image.onload = function(){
//context.drawImage(base_image, 0, 0);
scale_to_fit(this);
}
}
draw_image();
function scale_to_fit(img){
//get the scale
var scale = Math.min(frame.width/img.width, frame.height/img.height);
var x = (frame.width/2) - (img.width/2) * scale;
var y = (frame.height/2) - (img.height/2) * scale;
context.drawImage(base_image,x,y,img.width*scale, img.height*scale);
I found a similar post that suggested me to add this
document.addEventListener('DOMContentLoaded',draw_image,false);
saying the script is acting before the canvas is fully loaded, but it doesn't seem to be the issue.
Can anyone see where I'm possibly going wrong? Thanks ahead
EDIT!: It just occurred to me that the issue might be related to retrieving the image source location with Jinja?
It seems like my problem is not html/js related at all. I am using Jinja to retrieve the image location from the server, and Jinja doesn't serve to that external js file. It seems to me that function needs to be kept in the html file.
That's correct. Jinja doesn't run any processing on statically included assets.
I see two ways around your problem.
Either hard code the URL in script.js:
var image_url = '/path/to/image'
Or remove that line from the draw_image function and set that JS variable in the template, prior to including script.js:
<script type='text/javascript'>
const image_url = {{img_url}};
</script>
<script type='text/javascript' src="{{ url_for('static', filename='script.js') }}"></script>
I have hdf5 file created using c++ application.i want to read the same hdf5 file inside browser using javascript.
Hdf5 file will be download from server using xhr or web socket request and the content of the file will be stored in javascript variable then i want to read the content of the variable.
Please tell me any javascript library available to read the hdf5 inside browser.
i tried "https://github.com/HDF-NI/hdf5.node" but it supports only for nodejs.
Is it possible to convert the above library to support reading inside browser.
It is only able to read a subset of HDF5 files, but this is something that works:
https://github.com/usnistgov/jsfive
It basically covers all the files that can be read by the pyfive library (https://github.com/jjhelmus/pyfive), as it is a direct port of that library.
The best two libraries that I found are jsfive and h5wasm:
Sample code jsfive:
$(document).ready(function() {
$("#datafile").change(async function loadData() {
var file_input = $("#datafile")[0];
var file = file_input.files[0]; // only one file allowed
let datafilename = file.name;
let reader = new FileReader();
reader.onloadend = function(evt) {
let barr = evt.target.result;
var f = new hdf5.File(barr, datafilename);
let value = f.get('main').value
let attrs = f.get('main').attrs
// do somthing with f
}
})
})
<!DOCTYPE html>
<html lang="eng">
<head>
</head>
<body>
<input type="file" id="datafile" name="file">
<!-- Import JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Import JSFive -->
<script src="https://cdn.jsdelivr.net/npm/jsfive#0.3.7/dist/hdf5.js">
<!-- Import main JS -->
<
script src = "app.js" >
</script>
</body>
</html>
Sample code h5wasm:
import * as hdf5 from "https://cdn.jsdelivr.net/npm/h5wasm#latest/dist/esm/hdf5_hl.js";
await hdf5.ready;
$(document).ready(function() {
$("#datafile").change(async function loadData() {
let file = $("#datafile")[0].files[0];
let data_filename = file.name;
let ab = await file.arrayBuffer();
hdf5.FS.writeFile(data_filename, new Uint8Array(ab));
let f = new hdf5.File(data_filename, "r");
// do somthing with f
f.close()
})
})
<!DOCTYPE html>
<html lang="eng">
<head>
</head>
<body>
<input type="file" id="datafile" name="file">
<!-- Import JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Import main JS -->
<script type="module" src="app.js" ></script>
</body>
</html>
Also interesting jsfive with callback:
function storeTarget(result, file_name) {
f = new hdf5.File(result, file_name);
}
$("#datafile").change(async function loadSource() {
var file_input = $("#datafile")[0];
var file = file_input.files[0];
let datafilename = file.name;
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = () => storeTarget(reader.result, datafilename);
})
I have an external javascript file called test.js as seen below. This file needs user configuration parameters passed to it, in this case user and show values.
<script type="text/javascript">
<!--//
user = '123';
show = 'appts';
//-->
</script>
<script src="{{ STATIC_URL }}js/widgets/test.js" type="text/javascript"></script>
Above is currently how I tell 3rd parties to add the script to their own site. However, I cannot help to feel this is a bad way to pass these values i.e. clashes.
Is the way I have done it acceptable? Is there a better way?
A simple answer would be to append something to your variable names, such as:
<script type="text/javascript">
<!--//
widget_test_12331_user = '123';
widget_test_12331_show = 'appts';
//-->
</script>
You can stick to namespace convention "reverted domain":
<script type="text/javascript">
<!--//
if (!org) var org = {};
if (!org.mylibrary_domain) org.mylibrary_domain = {};
if (!org.mylibrary_domain.settings) org.mylibrary_domain.settings = {};
org.mylibrary_domain.settings.user = '123';
org.mylibrary_domain.settings.show = 'appts';
//-->
</script>
<script src="{{ STATIC_URL }}js/widgets/test.js" type="text/javascript"></script>
You can use the concept of javascript namespace (How do I declare a namespace in JavaScript?).
so you can add another js file named testConfig.js, which include :
var yourAppNamespaceTestConfig = {
user: function(){ return '123' ;} ,
show: function(){ return 'appts';}
};
then inside test.js, you can read the config by:
var user = yourAppNamespaceTestConfig.user();
var show = yourAppNamespaceTestConfig.show();
And if you're more about OO, try Coffeescript (http://coffeescript.org/). They introduce OO to your javascript.
I am currently doing this:
<div id="textChange" style="display:none;">Blah blah</div>
<script type="text/javascript">
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
</script>
and would like to move the script to an external JS file. How do I do that? I doesn't seem to be working for me.
Thanks.
Include this script after your #textChange div and it will work. For example before closing </body> tag:
...
<script src="funny-script.js" type="text/javascript"></script>
</body>
This is the simplest method. You could also run this code on DOMContentLoaded or window.onload events, but looking at what your script doing I don't think it makes sence.
1-open notepad or notepad ++ or whatever you use as a text editor.
2-copy the javascript code to the text editor without and tags
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
3-save the files with any name you want and don't forget to add the .js extension to the file for example save the file as "test.js"
4-copy the "test.js" to the same directory as html page.
5-add this line to the html page
<script type="text/javascript" language="javascript" src="test.js"></script>
One way to do this is to create a function and include this in a js file
function style_changer(){
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
Now in your html give reference to the js file containing this function for example
<script type="text/javascript" src="yourscriptfilename.js" />
you can include this in your section and should work
Save the a file called script.js with the contents.
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
And place this tag inside your HTML document. Place it just before the </body> so you'll know that the element textChange will exist in the DOM before your script is loaded and executed.
<script type="text/javascript" src="script.js" />
Make sure that script.js is in the same directory as your HTML document.
put this below code in a function
step1:
function onLoadCall()
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
Step2:-
call that function on page load
<body onload='onLoadCall()'>
...
</body>
step3:-
now move the script to another file it will work
Put script in a separate file and name it yourScript.js and finally include it in your file
add the code within the script file
function changeFunnyDate(){
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
Finally add the script in your file & call the method
<script src="yourScript.js" type="text/javascript"></script>
Take everything between your script tags and put it in another file. You should save this file with a .js file extension. Let's pretend you save it as textChange.js.
Now the simplest thing to do would be to include the script file just after your <div> tag -- so basically where the <script> tags and code were before, write:
<script type="text/javascript" src="textChange.js"></script>
This assumes that 'textChange.js' is in the same folder as your HTML file.
...
However, that would far too easy! It is generally best practice to place <script> tags in the <head> of your HTML file. You can move the line above up into the head but then the script will load before your <div> does--it will try to do what it does and it will fail because it can't find the div. So you need to put something around the code in your script file so that it only executes when the document is ready.
The simplest way to do this (and there may be better ways) is write the following...
window.onload = function () {
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if ((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
This will mean your script is in the head where it should be and that it only performs when your whole page is ready, including the div that you want to act on.
Hope this helps.