I originally had the following code commands for simplicity I put it just below the body in the html file.
This is my code:
<script>
async function ThemMonHoc() {
MyPopUpPost('Thêm môn học','/ThemMonHoc')
}
async function SuaTen() {
MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
}
async function MyPopUpPost(title,route) {
var a = await Swal.fire({
title: title,
html: '<input id="Result" class="swal2-input" type="text"></input>',
showDenyButton: true,
})
var value = $('#Result').val()
if (a.isConfirmed) $.post(route,{a:value})
}
</script>
It seems that the function MyPopUpPost will be reused many times in other html files and leaving the code here will not be very neat. So, I put it in another file.
This is my code in UtilitiesForm.js:
export async function MyPopUpPost(title, route) {
var a = await Swal.fire({
title: title,
html: '<input id="Result" class="swal2-input" type="text"></input>',
showDenyButton: true,
})
var value = $('#Result').val()
if (a.isConfirmed) $.post(route, {
a: value
})
}
And back to the html file I try import or require to use that function but it is not working:
<script>
import {MyPopUpPost} from '/js/UtilitiesForm.js'
async function ThemMonHoc() {
MyPopUpPost('Thêm môn học','/ThemMonHoc')
}
async function SuaTen() {
MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
}
</script>
Is there a way to redo the work between public JS files?
You have two options,
You can import your file into the HTML by using the script's src attribute.
Check this out: https://www.w3schools.com/tags/att_script_src.asp
Then, Change your script to the following and you should be ok:
<script src='/js/UtilitiesForm.js'></script>
<script>
async function ThemMonHoc() {
MyPopUpPost('Thêm môn học','/ThemMonHoc')
}
async function SuaTen() {
MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
}
</script>
add type="module" to your script.
Check this out: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-type
It seems you are doing it correct, just mention the type in script tag, make sure your path is correct to the JS file.
<script type="module">
import {MyPopUpPost} from '/js/UtilitiesForm.js'
async function ThemMonHoc() {
MyPopUpPost('Thêm môn học','/ThemMonHoc')
}
async function SuaTen() {
MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
}
</script>
I recommend you checking this link, how to import files in HTML.
If you want to use ES6 modules, you need type="module" on your <script> tag.
If you look in your browser's Console, it should probably tell you something to that effect.
But if you don't use ES6 modules, it will actually be simpler; things will be global by default and you don't need any import/export statements, you just include the utilities as a <script> before the main <script> code.
It's up to you which style to use; ES6 modules are cleaner, but require more management.
Related
This is the current snippet that is not running any of the Motoko scripts in edX when inserted onto a page.
All that is being parsed currently is the Html part.
Are the scripts pointing to the correct file locations or have I done something wrong during the upload process?
<div id="counter" class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-motoko hljs" data-lang="motoko">actor Counter {
var value = 0;
public func inc() : async Nat {
value += 1;
return value;
};
}</code></pre>
</div>
</div>
<!-- Start of dfinity Zendesk Widget script -->
<script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=53121947-c10a-484c-b99b-f89a9fb6f63e"> </script>
<!-- End of dfinity Zendesk Widget script -->
<script async type="text/javascript" src="https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#behavior.js"></script>
<script async type="text/javascript" src="https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#highlight.bundle.js"></script>
<script type="text/javascript" src="https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#run_repl.js"></script>
<script type="module">
import {CodeJar} from 'https://cdn.jsdelivr.net/npm/codejar#3.2.3/codejar.min.js';
import {withLineNumbers} from 'https://cdn.jsdelivr.net/npm/codejar#3.2.3/linenumbers.js';
window.CodeJar = CodeJar;
window.withLineNumbers = withLineNumbers;
</script>
<script type="module">
import {CodeJar} from 'https://medv.io/codejar/codejar.js'
</script>
<script type="text/javascript">
async function addPackage(name, repo, version, dir) {
const meta_url = `https://data.jsdelivr.com/v1/package/gh/${repo}#${version}/flat`;
const base_url = `https://cdn.jsdelivr.net/gh/${repo}#${version}`;
const response = await fetch(meta_url);
const json = await response.json()
const promises = [];
const fetchedFiles = [];
for (const f of json.files) {
if (f.name.startsWith(`/${dir}/`) && /\.mo$/.test(f.name)) {
const promise = (async () => {
const content = await (await fetch(base_url + f.name)).text();
const stripped = name + f.name.slice(dir.length + 1);
fetchedFiles.push(stripped);
Motoko.saveFile(stripped, content);
})();
promises.push(promise);
}
}
Promise.all(promises).then(() => {
Motoko.addPackage(name, name + '/');
console.log(`Loaded motoko library "${name}"`);
changeCodeBlock(); // from run_repl.js
});
}
function loadBase() {
addPackage('base', 'dfinity/motoko-base', 'dfx-0.8.4', 'src');
}
</script>
<script async src="https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#moc-interpreter-0.6.20.js" onload="loadBase()"></script>
after looking through your code there's a few missing pieces that may solve the problem.
The hightjs script is missing, which you can either attach to the head or body. You can choose to include their stylesheet or not.
https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/default.min.css
https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js
The run_repl here (https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#run_repl.js) has unexpected characters (backslashes) such that the file is not truly working. Please copy and replicate from here: https://github.com/dfinity/antora-sdk/blob/master/src/js/vendor/run_repl.js
There's some styling added inside Dfinity's website, which has been referenced. I've pulled it into a stylesheet on this replit project. Take a look!
https://replit.com/#Sue-AnnAnn/Motoko-highlight#index.html
There is an easier solution now!
https://embed.smartcontracts.org/motoko/g/3oBbKveNbudpGgKMb2A5wADMcv3U6CDvxfjKMvASfcmkuXEk9j7UtFCn2DpHrUVJ3dSJYEMu2bW54vZRiPhYk4MDgdXkQhHwt1HhmcLi3GpCowBeaYus4BUpMZNDMLKezqBwcMg7EXFbVvNYR5xp57dViryE9uawnFjkuZacyor5jp?lines=10
Copy the iframe code and embed it into a raw HTML page on EDX.
I tried to use click on button:
#app.route("/")
def test_edition_open():
return render_template("index.html")
my index.html file is:
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
The main part is just two buttons:
<div class = "counter">
<button class = "minus">-</button>
<div class = "result">1</div>
<button class = "plus">+</button>
</div>
I tried to make My script.js file work in flask. The code is very simple, it should add numbers by clicking on button:
const plus = document.querySelectorAll('.plus');
const minus = document.querySelectorAll('.minus');
const result = document.querySelectorAll('.result');
function min()
{
return function (ev)
{
if (ev.target.nextElementSibling.innerHTML > 0)
{
return --ev.target.nextElementSibling.innerHTML;
}
}
}
function pl()
{
return function (ev)
{
return ++ev.target.previousElementSibling.innerHTML;
}
}
minus.forEach(function (dominus)
{
dominus.addEventListener('click', min());
})
plus.forEach(function (doplus)
{
doplus.addEventListener('click', pl());
})
In https://playcode.io this code worked well. How should I solve this problem?
Make sure that script file successfully connected to html file. to check this add console.log("File Connected") in your script.js file. Then open your browser console to check that console message is logged correctly. If not then try to linked your static file correctly. How to set static_url_path in Flask application
Or you can put your Javascript code in html file using script tag.
Something like this:
<script> your javascript code here</script>
I want to call a function 'addArray' in a separate .js file called 'main.js'
When I run this code, I get an error saying the 'addArray' is not defined in checkout.js
I don't want it to look for the function in checkout.js, I want it to look for the function in main.js
I am using node.js
<body onload="myFunction()">
<script src = "https://www.paypalobjects.com/api/checkout.js"></script>
<script type = "text/javascript" src = "main.js"></script>
<div class="container">
</div>
<script>
paypal.Button.render(
{
onAuthorize: function(data, actions)
{
return actions.payment.execute().then(function()
{
// Show a confirmation message to the buyer
days = 30
localStorage.setItem("days", days);
inputDays = JSON.parse(localStorage.getItem('days'));
inputName = localStorage.getItem('name');
window.alert('Thank you for your purchase!');
console.log(inputDays);
console.log(inputName);
addArray();
});
}
}, '#paypal-button');
I had to delete most of the intermediate non essential code for the purpose of submitting this question
So... There are a few things I think you should check for.
If you are using commonJS, be sure that you are exporting the addArray function like so: module.exports = {addArray}; Then require it from your main.js file.
If you are using es6 syntax, you can export it like export default addArray or export {addArray}, then import it in your main.js file using the import {addArray} from... or import addArray from ... depending on the export style you used.
Hello !
I tried using import/exports for the first time, and I have this issue in my code :
The requested module '../Ajout/script.js' does not provide an export named 'flagMap'
I have these files Supprimer.js, containing at the first line :
import{flagMap, findUrl, createUrl,texteValide} from '../Ajout/script.js';
And in Ajout.js contained in another forlder in the parent folder:
var flagMap={/*really long map*/}
function findUrl(isoCode){/*long url finder*/}
function createUrl(svgUrl) {
return `https://upload.wikimedia.org/wikipedia/${svgUrl}`;
}
function texteValide(element){/*text validation for a form*/}
export{flagMap,findUrl,createUrl,texteValide};
/*
other non-exported functions
*/
There is the type="module" in my html when I'm importing the script, and my Ajout.js also contains other functions, maybe it's causing issues ?
Also : The issue is not only flagMap but every import, because it shows another file if I remove flagMap from the imports
This works fine for me:
<!-- index.html -->
<html>
<head> ... </head>
<body>
<script type="module" src="path/to/Supprimer.js"></script>
</body>
</html>
// Ajout.js
var flagMap = {
// ...
};
function findUrl(isoCode) {
// ...
}
function createUrl(svgUrl) {
// ...
}
function textValide(element) {
// ...
}
// Export functions and variables
export {
flagMap,
findUrl,
createUrl,
texteValide
};
// Supprimer.js
import { flagMap, findUrl } from "path/to/Ajouter.js";
console.log(flagMap); // Prints map
findUrl("EN"); // Can call function
I have these js files:
main.js:
requirejs(['app']);
app.js:
define(['messages'], function (messages) {
alert(messages.getHello());
});
messages.js:
define(['global'],function () {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
global.js:
define(function () {
var stateObj = {hello:"test!"};
return {
getObj: function () { return stateObj; }
};
});
and index.html as:
<!DOCTYPE html>
<html>
<head>
<!-- Include the RequireJS library. We supply the "data-main" attribute to let
RequireJS know which file it should load. This file (scripts/main.js) can
be seen as the entry point (main) of the application. -->
<script data-main="scripts/main" src="lib/require.js"></script>
</head>
<body>
<h1>Example 2: load module using explicit dependency syntax</h1>
</body>
</html>
However when I open index.html, I get the below error in console:
Uncaught ReferenceError: global is not defined messages.js
where I'm making mistake?
You just need to set global as an argument to messages.js' function. requirejs will pass it in for you.
messages.js:
define(['global'],function (global) {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
This has the neat side effect that it is impossible to reference a module without declaring it as a dependency.