I’m using flask for web dev apps. I want to use javascript framework for frontend. so what is a good JavaScript framework that use for front-end and with flask framework?
Category: javascript
Category Added in a WPeMatico Campaign
How event handler inside JavaScript class/function got called?
I’m quite new on JS and got stuck on this problem. So I have this constructor which I understand how its works EXCEPT for one thing. How does an event handler got called from inside of an object or function?
I thought event handler could only be placed on global scope directly, not inside a function/object or another block scopes.
class Counter {
constructor(element) {
this.element = element;
this.value = value;
this.valueDOM = element.querySelector('.value');
this.valueDOM.textContent = this.value;
this.increase = this.increase.bind(this);
this.btnIncrease = element.querySelector('.increase');
this.btnIncrease.addEventListener('click', this.increase);
}
increase() {
this.value++;
this.valueDOM.textContent = this.value;
}
}
const counterOne = new Counter(document.querySelector('.counter-one'));
const counterTwo = new Counter(document.querySelector('.counter-two'));
The HTML is quite simple, just a plain counter like this.
<div class="container counter-one">
<span class="value">0</span>
<button class="increase">+</button>
</div>
<div class="container counter-two">
<span class="value">0</span>
<button class="increase">+</button>
</div>
deployed reactjs page with server (express) only works on pc but not on my phone
The page works fine when in localhost:3000. I can access it from phone and pc. When deploying the project to github pages and then accessing it via github.io page, the client works fine on PC after starting the proxy (localhost:5001) on my pc. But not on my phone – the client does not fetch from the server even though I’m connected to the same network. The client is being displayed, but no connection to the proxy seems to be established
In the clients package.json, i have "proxy": "http://localhost:5001/"
And the fetching is done in this manner:
export default async function request({zon, pc}) {
const response = await fetch('http://localhost:5001/getInfo',
{
method: "POST",
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"outletId": zon,
"providerCode": pc
})
})
const xam = await response.json();
console.log(xam);
return xam;
}
and my server.js, which is outside of the client folder (acts like a proxy), looks like the following:
let cors = require("cors");
app.use('/newsApi', proxy(newsApiUrl)); */
app.use(cors());
app.use(express.json());
app.use(express.static(__dirname, { dotfiles: 'allow' } ));
// app.use(express.static(path.join(__dirname, '/dist/')));
app.listen('5001', 'localhost', function () {
console.log("App listening on port 5001");
});
app.post('/getInfo',cors(), function (req, res) {
let message = {
"outl": req.body.outl,
"provi": req.body.provi
};
console.log(req.body.outl);
handleSynchronousRequest(message, "APP_GET_OUTLET_STATUS_REQUEST", res);
});
the method handleSynchronousRequest performs request to the server from the proxy file above.
I actually wanted to remove localhost:5001 from const response = await fetch('http://localhost:5001/getInfo' and only have /getinfo but it wont work if done so.
How can i disable button on another page when i press a button on this page and also save the disabled button to local storage
Trying to disable a button on another page by pressing a button on this page.
WHAT I TRIED: Right now when the button is pressed it creates a function and the function says this
function createItem() {
localStorage.test1 = document.getElementById("hello").buttonDisabled="disabled";
}
On the other page i have another button which has a function which gets that saved item from local storage and applies it to the button to disable it. I know thats working properly
localStorage.test1 = document.getElementById("hello").buttonDisabled="disabled";
I just need help on changing this part “buttonDisabled=”disabled”” so it actually disables the button instead of what its currently doing which is just changing the text thats on the button.
Also the codepen link for this is
https://codepen.io/haroon1233212/pen/XWVqrbe
the code you need to change is at the bottom of the page in the javascript section
Select box options are not loading after assignment
I am currently developing a school awards website, and I have stumbled upon an interesting issue that I can’t find a fix for. The voting form has a grade select box where you can select the grade of the nominee, after you select the grade, the box gets replaced with a different select box where you choose the nominee himself.
While the box is getting replaced I fetch all the people from the selected grade and put them into an array, then get the names of those people, create an option, and put it all into a variable
const [nomVisibility, setNomVisibility] = React.useState("none");
const [classVisibility, setClassVisibility] = React.useState("inline");
function handleCandidates() {
setClassVisibility("none");
renderDivs();
setNomVisibility("inline");
}
const classmates = [<option key="sts">Select the student</option>];
function renderDivs() {
fetch(`http://localhost:3000/api/allusers/pretendThatHereIsASecurityCode`)
.then((res) => res.json())
.then((data) => {
setUData(data);
let newArray = data.data.filter(function (el) {
console.log(el);
return el.grade === selectValue;
});
console.log(newArray);
for (let index = 0; index < newArray.length; index++) {
const element = newArray[index];
let nameSurname = element.name + " " + element.surname;
classmates.push(
<option key={element.name + element.surname}>{nameSurname}</option>
);
console.log(classmates);
}
return classmates;
});
}
here’s the HTML code and gif where I display how does everything exactly look like https://gyazo.com/fa663531f1d65947604acef155886951
<select
className={styles.nominations}
name="candidates"
style={{ display: classVisibility }}
onChange={(e) => {
setSelectValue(e.target.value);
}}
>
<option value="7.1">7.1</option>
<option value="7.2">7.2</option>
<option value="7.3">7.3</option>
<option value="7.4">7.4</option>
<option value="8.1">8.1</option>
<option value="8.2">8.2</option>
<option value="8.3">8.3</option>
<option value="8.4">8.4</option>
<option value="9.1">9.1</option>
<option value="9.2">9.2</option>
<option value="9.3">9.3</option>
<option value="9.4" onClick={handleCandidates}>9.4</option>
</select>
<select
className={styles.candidates}
style={{ display: nomVisibility }}
id="candidates"
>
{classmates}
</select>
How do I change a Boolean variable’s value from a grandchild component in this Vue 3 application?
I am working on a Vue 3 app. I have 3 nested components: a button component, which is nested inside a navigation component, which is nested inside a content component.
The button should toggle the value of the boolean variable isVisible inside the grandparent component Main.vue (content component).
In the grandchild component MyButton.vue:
<template>
<button @click="handleClick" class="btn btn-sm btn-success">
{{ label }}
</button>
</template>
<script>
export default {
name: 'MyButton',
props: {
label: String,
isVisible: Boolean
},
emits: [
'toggleVisibility',
],
methods: {
handleClick() {
this.$emit('toggleVisibility')
}
}
}
</script>
In the parent component Navigation.vue:
<template>
<div class="navigation">
<MyButton
:label='"Toggle content"'
:isVisible=false
@toggleVisibility="$emit('toggleVisibility')"
/>
</div>
</template>
<script>
import MyButton from './MyButton'
export default {
emits: [
'toggleVisibility',
],
}
</script>
In the grandparent component Main.vue:
<template>
<div class="main">
<Navigation />
<div v-if="isVisible" class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
</div>
</template>
<script>
import Navigation from './Ui/Navigation'
export default {
name: 'Main',
components: {
Navigation
},
props: {
title: String,
tagline: String,
},
data() {
return {
isVisible: false,
}
},
methods: {
toggleVisibility() {
console.log('ok');
this.isVisible = !this.isVisible;
}
}
}
</script>
The problem
As can be seen above, I tried to emit upwards, one component at a time.
For a reason I was unable to understand, this does not work.
Questions
- Where is my mistake?
- What is the shortest viable solution?
Single file Angular application not displaying Material styles
I need my Angular app to be completely self contained so it’s browsable when opened from file explorer rather than served from a website. I’ve made a simple example which uses Material:
ng add @angular/material
ng add ngx-build-plus
app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<div>
<mat-slider min="1" max="100" step="1" value="50"></mat-slider>
</div>
</div>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatSliderModule } from '@angular/material/slider';
import { SliderComponent } from './slider/slider.component';
@NgModule({
declarations: [
AppComponent,
SliderComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatSliderModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularTourOfHeroes</title>
<base href="#"> <!-- Updated from "/" -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<app-root></app-root>
</body>
</html>
When served with ng serve, the page correctly renders like so:
If I build the project using ng build --prod --single-bundle and open the resulting html file in the browser, I see no errors in the Network or Console, but the slider doesn’t render:
Can’t find any tags using NodeJS, puppeteer, and document.querySelector
I have a NodeJS Typescript project, and I am trying to get all the ‘p’ tags from a dynamically rendered website (not STATIC HTML but instead makes multiple requests to backend to get some data and render webpage). I am using typescript and have [“es6”, “dom”] in my lib, and I have the following code (this is all my code in the project so far):
import puppeteer from 'puppeteer';
const getLinks = async () => {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.goto('https://webscraper.io/test-sites', { waitUntil: 'networkidle0' });
const links = await page.evaluate(() => document.querySelectorAll('p'));
console.log(links);
await browser.close();
}
However, I keep getting undefined when I print links. I assume this is because the program can’t find any ‘p’ tags. Why is this?
Note: the url provided is just an example. I have tried across multiple different sites and I still get undefined.
Any help is appreciated! Thanks!
Scientific notation with javascript
I am developing a site with javascript, which does the following, the visitor will enter the unit quantity, the unit to compare and the unit of comparison (Ex: 12 centimeters for millimeter) and it will show how much the quantity of the unit to compare is equivalent to the unit of comparison, the only problem is that if I put a unit to compare too small and a unit to compare too large, it will happen that the result will be wrong (Ex: 17 decimeters for kilometers will give 0, 0170000000000001) so I asked a person and they replied that I should use scientific notation, but I have no idea how to do it in javascript, could anyone help me?
Firefox full version number in HTML file
I have built an HTML start page that can be expanded according to your own wishes. The experts among you certainly see a lot of room for improvement.
However, I am currently trying to automatically enter the current full version number of the Firefox browser in line 106, where the number 99 is currently located.
I’ve already spent a lot of time on this, but I can’t find a suitable solution.
That’s why I’m asking you, does anyone have a suitable idea?
Here is the code:
<!DOCTYPE html>
<html lang="de">
<head>
<title>Menue</title>
<meta charset="utf-8" />
<style>
body { background:url(ff3.jpg) fixed; margin:0px; zoom:1.00; -moz-transform:scale(1.00); }
a:link { text-decoration:none; font-weight:normal; color:#3246ff; }
a:visited { text-decoration:none; font-weight:normal; color:#800000; }
a:hover { text-decoration:none; font-size:115%; color:#FFFFFF; background-color:#800000; border-radius: 80px !important; border:none!important; }
a:before { content: "» "; color:#000000; }
/* grid layout, 3 columns */
.wrapper {
display: grid; /* display: inline-grid;*/
grid-template-columns: 1fr 1fr 1fr; /* 3 x 1 fraction */
align-content:space-center;
justify-content:center;
margin-top: 50px;
}
:hover {
animation-play-state: paused;
}
.scroller {
width: 30px;
height: 100px;
overflow-y: scroll;
scrollbar-color: rebeccapurple green;
scrollbar-width: thin;
}
.example1 {
height: 80px;
color:#800000;
overflow: hidden;
position: relative;
}
.example1 h3 {
position: absolute;
width: 120%;
height: 90%;
margin: 0;
line-height: 90px;
text-align: center;
/* Starting position */
-moz-transform:translateX(100%);
-webkit-transform:translateX(100%);
transform:translateX(100%);
/* Apply animation to this element */
-moz-animation: example1 25s linear infinite;
-webkit-animation: example1 25s linear infinite;
animation: example1 25s linear infinite;
}
/* Move it (define the animation) */
@-moz-keyframes example1 {
0% { -moz-transform: translateX(100%); }
100% { -moz-transform: translateX(-100%); }
}
@-webkit-keyframes example1 {
0% { -webkit-transform: translateX(100%); }
100% { -webkit-transform: translateX(-100%); }
}
@keyframes example1 {
0% {
-moz-transform: translateX(100%); /* Firefox bug fix */
-webkit-transform: translateX(100%); /* Firefox bug fix */
transform: translateX(100%);
}
100% {
-moz-transform: translateX(-100%); /* Firefox bug fix */
-webkit-transform: translateX(-100%); /* Firefox bug fix */
transform: translateX(-100%);
}
}
</style>
</head>
<body>
<br><br>
<div style="display: table; width: 100%; height: 100px;">
<figure style="display: table-cell; padding: 0 4px; text-align: center;"><img src="pag37.gif"></figure>
<figure style="display: table-cell; padding: 0 4px; text-align: center; vertical-align: middle;"><img src="pag107.gif"></figure>
<figure style="display: table-cell; padding: 0 4px; text-align: center;"><img src="pag37.gif"></figure>
<figure style="display: table-cell; padding: 0 4px; text-align: center; vertical-align: middle;"><img src="pag107.gif"></figure>
<figure style="display: table-cell; padding: 0 4px; text-align: center;"><img src="pag37.gif"></figure>
</div>
<script>
var fullVersion = ''+parseFloat(navigator.appVersion);
var fullVersion = nAgt.substring(verOffset+8);
var vers = fullVersion
if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
</script>
<div class="example1">
<h3 style="font-size:22px">+++ Achim's Internetportal - Betriebssystem Linux Mint 19.3 mit Firefox Browser $(fullVersion) in der 64 Bit-Version +++</h3>
</div>
</body>
</html>
<table border="5" cellspacing="5" bordercolor=#990000 height="420px" width="100%">
<tr style="font-family:Verdana; font-style:bold italic; font-size:16px;">
<td width="33%" valign="top">
<ul>
<a HREF="https://www.chip.de/" target="_blank">Chip - Online</a> Computer-Nachrichten «<br>
</ul>
</td>
<td width="33%" valign="top">
<ul>
<a HREF="https://www.linuxmintusers.de/" target="_blank">Linuxmintusers</a> Systemunterstützung «<br>
</ul>
</td>
<td width="33%" valign="top">
<ul>
<a HREF="https://www.tippscout.de/computer/linux" target="_blank">Tippscout</a> praktische Tipps zu Linux «<br>
</ul>
</td>
</tr>
</table>
count how many bills javascript
You are shopping for an item, but the seller only allows
You have to pay with the appropriate number of bills
his request. Make a function to determine the fraction of the eye
the money needed to pay for the item.
Input
item_price, quantity_sheet
0 < item price < 100000
0 < sheet_number < 10
Input Example 1
17000, 1
Expected Output
[20000]
Explanation
To fulfill a transaction of 17000 with 1 banknote, then
The closest currency denomination that can be used is the 20000 denomination.
*nb money nominal = [1000, 2000, 5000, 10000, 20000, 50000, 100000]
i have try to code
const money = [1000, 2000, 5000, 10000, 20000, 50000, 100000];
function countBankNotes(price, banknotes) {
const result = [];
let temp = 0;
let priceItem = price;
let bankNotes = banknotes;
for (let i = 0; i < bankNotes; i++) {
for (let j = 0; j < money.length; j++) {
if (
priceItem < money[j] &&
temp <= bankNotes
) {
temp ++;
result.push(money[j-1])
priceItem = priceItem - money[j-1];
console.log(priceItem)
break;
}
}
}
return result;
}
console.log(countBankNotes(17000, 1));
Why does visual studio code exe publish throws error?
error image below
Check this image i’m getting this error .when i was publishing vsce
How to animate visibility of mesh in react three fiber?
I have a 3D model. I have the access to the mesh. What I want is to animate the visibility on button click. When I press a button the mesh should be invisible but not instantly. I want to make it in an animated way. It will be invisible in some steps. Like taking 2 sec of time to be invisible with a transition. How can I do that with react three fiber? I’m new in React-three/fiber.
Firefox extension inject script into page
I use this script in the background page to inject script into page and it works well on click on the extension icon
browser.browserAction.onClicked.addListener(function (tab) {
// for the current tab, inject the "inject.js" file & execute it
browser.tabs.executeScript(tab.id, {
file: 'inject.js'
});
});
I want it to inject the script auto when page load. I used onload and onupdate but not work
Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(…) is null when calling set function
I’m trying to set up a user login system using the userContext and localSotrage of the browser.
I have a first file that includes my provider and my context:
Auth.jsx
import { hasAuthenticated } from '../services/AuthAPI';
export const AuthContext = createContext()
const AuthProvider = ({children}) => {
const [auth, setAuth] = useState(hasAuthenticated());
const value = useMemo(() => ({auth, setAuth}, [auth, setAuth]));
return (
<AuthContext.Provider value={value}>{children}</AuthContext.Provider>
)
}
export default AuthProvider
export const AuthState = () => {
return useContext(AuthContext)
}
I also have a page that allows to manage elements of the LocalStorage and to know if a user is already connected (it for now hardcoded):
AuthAPI.jsx
export function hasAuthenticated() {
const token = getItem('sessionToken');
const result = token ? tokenIsValid(token) : false;
if (false === result) {
removeItem('sessionToken');
}
return result;
}
export function login(credentials) {
addItem('sessionToken', 'tokenSample');
return true;
};
export function logout() {
removeItem('sessionToken');
}
function tokenIsValid(token) {
// const { exp: expiration } = jwtDecode(token);
// if (expiration * 1000 > new Date().getTime()) {
// return true;
// }
return true;
}
And finally I have my connection page which must update the auth variable using the context:
Login.jsx
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../contexts/Auth';
import { login } from '../services/AuthAPI';
const Login = () => {
const navigate = useNavigate();
const {auth, setAuth} = useContext(AuthContext);
const [user, setUser] = useState({
username: "",
password: ""
})
const handleChange = ({ currentTarget }) => {
const { name, value } = currentTarget;
setUser({ ...user, [name]: value })
}
async function handleSubmit(event) {
event.preventDefault();
try {
const response = await login(user);
setAuth(response);
navigate('news', { replace: true });
console.log('oui');
} catch (e) {
console.error(e);
}
}
useEffect(() => {
if (auth) {
navigate('news', { replace: true });
}
}, [navigate, auth]);
return (
<div className="container border rounder mt-5 p-3 bg-light">
<form className="form-profile" onSubmit={setAuth(true)} >
<fieldset>
<legend>Se connecter</legend>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="text"
name="username"
className="form-control"
id="email"
placeholder="[email protected]"
onChange={handleChange}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
className="form-control"
id="password"
placeholder="Password"
onChange={handleChange}
/>
</div>
<button type="submit" className="btn btn-outline-primary">
Se connecter
</button>
</fieldset>
</form>
</div>
);
};
export default Login;
But React returns this error:
Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(…) is null site:stackoverflow.com
Do you have any idea ?

