Having trouble with ES6 import / export variables - javascript

I am trying to compare text from two HTML pages using javascript using two separate external js files and importing the needed variable to be compared. However the function is not showing any result.
My first html is:
<!DOCTYPE html>
<html>
<body>
<span id='current-name'>John Hamish Smith</span>
<p id='new-billing'>0</p>
<script src='experiment.js' type="text/javascript"></script>
</body>
</html>
experiment.js below:
const currentName = document.getElementById('current-name').textContent;
const newBillingField = document.getElementById('new-billing');
const currBillingValue = Number(newBillingField.textContent);
let newBillingValue = currBillingValue + 1;
import {nameCheck} from './test2';
const testing = () => {
if(currentName === nameCheck) {
newBillingField.textContent = newBillingValue;
alert('hi there');
}
}
window.addEventListener('load', testing);
then my second html is simply:
<!DOCTYPE html>
<html>
<body>
<p id='userName'>John Hamish Smith</p>
<script src='./test2.js' type='text.javascript'></script>
</body>
</html>
and test2.js as follows:
let nameCheck = document.getElementById('userName').textContent;
export {nameCheck}
However, even with the names being the same, my newBillingValue is still 0.
(the alert is just to facilitate the function test)
thank you!

Related

How to show the output of a function that takes two arguments in brython?

I have this brython script that is supposed to take in two inputs, process them in a python function imported from another python file, and generate one output into a textarea when the inputs are typed in. I can't figure out how to do that as the bind() only allows one.
Here is how the process looks like
The following code only works with one input
<textarea id="input_one"></textarea>
<textarea id="input_two"></textarea>
<textarea id="output"></textarea>
<script type="text/python">
import project
from browser import document
def function(x):
document['output'].text = project.main(x.target.value)
document['input_one'].bind('input', function)
</script>
Assign names to the fields in the document and refer to them in the bound function.
That way you can retrieve their values and pass them along to project.main.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.10.7/brython.min.js">
</script>
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.10.7/brython_stdlib.js">
</script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document
import project
element_x = document['input_one']
element_y = document['input_two']
element_result = document['output']
def oninput(arg):
x, y = None, None
try:
x = int(element_x.value)
y = int(element_y.value)
except ValueError:
pass
if x and y:
element_result.value = project.main(x, y)
else:
element_result.value = ''
element_x.bind('input', oninput)
element_y.bind('input', oninput)
</script>
<input id="input_one"></input>
<input id="input_two"></input>
<input id="output" disabled></input>
</body>
</html>

JavaScript - Call function from another module inside HTML page

I have a module i18n.js which I import in my home.html, like this:
<html>
<head></head>
<body>
<script type="module" src="../js/lib/i18n.js"></script>
</body>
</html>
Inside the i18n.js module, I do the following:
export const t = () => {};
//
// Global scope
//
window.t = t;
I understand that accessing the global window object is the way to go in order to be able to call a method from other file inside an HTML page. But... why is this code not working?
<html>
<head></head>
<body>
<p><script>t("title")</script></p>
<script type="module" src="../js/lib/i18n.js"></script>
</body>
</html>
I get the error:
Uncaught ReferenceError: t is not defined
Because you're trying to execute t before it's available on the window, you get an error but running the function through the onload as #Rajesh suggested works properly.
const t = () => {
const pTitle = document.getElementById('pTitle');
if (pTitle){
pTitle.textContent = 'Hello World!';
}
};
//
// Global scope
//
window.t = t;
export {
t
};
<html>
<head></head>
<body onload="t()">
<p id="pTitle"> </p>
<script type="module" src="./src/js/i18n.js"></script>
</body>
</html>

How can I use a parameter to change HTML text?

I'm using an API, and am trying to access the value of product.shoeName to change text on my HTML page. This is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="shoepoo.js">
</script>
</head>
<body>
<div>
<p id="text" style="color:purple;
font-weight:bold;font-size:20px;">
</p>
<script type="text/javascript"> shoeName(); </script>
</div>
</body>
</html>
const SneaksAPI = require('sneaks-api');
const sneaks = new SneaksAPI();
//getProducts(keyword, limit, callback) takes in a keyword and limit and returns a product array
function shoeName(){
sneaks.getProducts("Jumbo Blazer", 1, function(err, products){
products.forEach(
function names (product) {
document.getElementById("text").innerHTML = product.shoeName;
})
});
};
Basically, I want product.shoeName to be shown as text, but nothing is showing up. How can I fix this? I understand it's a local function which is probably stopping the data from being shown (or something like that), but how can I work around this?
Made below changes in shoepoo.js
products.forEach((product)=> {
document.getElementById("text").innerHTML = product.shoeName;
});
But you need to create dynamic HTML components if there is multiple data in products. Otherwise, it set the last shoeName in the paragraph component.

Why is dom.innertext was updated and rendered after the while is finished in this example?

I am pretty new to javascript and am working on an assignment.
The problem I have can be demonstrated via codes below:
For HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A3Q5</title>
<script src='xxx.js'> // external js
</script>
</head>
<body>
<div class="container">
<button id="startBtn">Start</button>
<div id="displayStart">x</div>
</div>
</body>
</html>
For the xxx.js code:
function setup(){
document.getElementById("startBtn").addEventListener('click',startRace,false);
}
function startRace(){
var test = document.getElementById("displayStart");
test.textContent = "adsasdasds";
console.log(test.textContent);
var c = 5;
while(c--){
var counter = 500000000;
while(counter--){} // try to simulate some delays
}
}
window.addEventListener('load',setup,false);
so the problem is, when I run the program and click the button, the console prints "adsasdasds" however the div element is not updated in the browser until the first while loop is done....
Doesn't js run sequentially like java / C++ if no async is specified ?
Hope someone can help me out
The desired result will be : the div is updated before entering the while loop as the sequence of code execution...
Thank you !

Why isn't html running javascript I import when I use import-export

My code works fine when I add my module straight into the html code, but it won't load it when I try to first import the module to a different javascript file.
I've tried exporting everything, from my module.
HTML:
<html>
<head>
<title>
Hello world
</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Tradingpost, done by no css gang.</h1>
<div id="sidenav">Here be the links to other pages</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script src="js/app.js"></script>
</body>
</html>
app.js:
import * as sidebar from "./visualModules/sidebarmodule"
function cumulator() {
sidebar.createSidebar()
}
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
It should add elements to the div. But it wont do it unless I straight up use the sidebarmodule.js. I want to do it through the app.js
EDIT
Found the problem!
Didn't initialize index in the for loop.
EDIT2
And the type="module" which needed to be added
When you load your app.js in your html file, try to add:
<script type="module" src="js/app.js"></script>
That should work when you want to use ESModules. But please update us regardless :)
Update:
Ok after creating a project myself using your HTML and JS, I found a few errors.
First: When using ESModules, you can't use any functions in the JS through your HTML, you will have to inject everything from the app.js.
index.html:
<body>
<div id="sidenav">
Here be the links to other pages
</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script type="module" src="js/app.js"></script>
app.js:
import { createSidebar } from './visualModules/sidebarmodule.js';
cumulator();
function cumulator() {
createSidebar()
}
Notice two things: at the end of the import, since we are not using a compiler, the modules do not recognize files without their extension. So I had to add .js to sidebarmodule. Secondly, I had to invoke cumulator function within the app.js file (like I said earlier, you cannot use any module functions outside their scope. There are no global variables with ESModules).
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(var index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
You did not declare index inside your for loop, so I just added a var.
Hope this helps.
import is asynchronous in Javascript (in a browser, not Node.js) so you're calling createSidebar() before the module is loaded. You can use import to return a promise so you can execute code once it is completed.
Remove the embedded Javascript from your html, but leave the link to app.js. Then change app.js to this...
import("./visualModules/sidebarmodule")
.then((sidebar) => {
sidebar.createSidebar();
});

Categories