Category: javascript
Category Added in a WPeMatico Campaign
Javascript – How to prevent functions from multiplying themselves [closed]
I’m struggling.
I’m doing some work to make navigation fully accessible by mouse over, keyboard and click, depending on the resolution.
I am looking for that in mobile, only the click works.
And hover, click, keyboard for higher resolutions.
It only works perfectly when I load the page at the correct resolution (low or high).
BUT, if I resize live, my functions multiply by themselves by the number of resizes done.
I tried a lot of thing like e.stopPropagation
, bubble
, return
, split functions, all in one…without success.
-
Here is a example of the problem with a factice code, shorter (maybe it could be suffisant to understand the solution with your help) :
Need to reduce and maximize screen and click the button for testing.
https://codepen.io/TanGo21/pen/RwLNWey -
Here is, a part of my “real” code :
Go under 770px, then maximize, and look the console when you go over item “THREE” who contains a submenu.
https://codepen.io/TanGo21/pen/oNGgxBK
Angular: utils/util.js -> Uncaught ReferenceError: process is not defined
I feel like this should be resolved simply, but after several attempts, I’m just not coming to a resolution.
Here is the error I’ve received:
Uncaught ReferenceError: process is not defined
38509 @ [PathToProject]node_modulesutilutil.js:109
This is getting triggered when I instantiate web3 into a clean/new site (there’s two other ‘test’ components, one link one button)
I’ve searched and found numerous bits of information suggesting that
- process is a server side ‘node’ var, and I can set this to be available client-side by adding to my webpack.config.js, which I have done.
- I might be able to resolve by just declaring a global angular var in my app.component.ts, but it seems this dependency project .js file is not accessing it.
I’ve also tried just updating the dependency project directly, but even with a compile, it seems that my changes are not being distributed into the webpack build /dist/ result.
I think this probably has a blatantly simple solution, but I’m just overlooking it. I’m just spinning my tires here and could use a little help, but I’m the first in my circle to venture into web3 and don’t have a close friend to bounce this off of. Can someone here provide some insight or an alternative resolve this issue?
Relevant bits of code:
webpack.config.js
var webpack = require('webpack');
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /.(sass|less|css|ts)$/,
use: [
'ts-loader'
],
}
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': 'develop',
})
],
entry: './src/main.ts',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
extensions: [ '.js', '.ts', '.html' ],
modules: [
path.resolve(__dirname, 'node_modules/'),
path.resolve("", "src")
],
alias: {
Environments: path.resolve(__dirname, 'src/environments/'),
},
fallback: {
"fs": false,
"tls": false,
"net": false,
"path": false,
"zlib": false,
"http": require.resolve("stream-http"),
"https": require.resolve("https-browserify"),
"stream": false,
"crypto": require.resolve("crypto-browserify"),
"crypto-browserify": require.resolve('crypto-browserify'),
},
}
}
global-constants.ts
export class GlobalConstants {
public static process: any = {
env: {
NODE_ENV: 'development'
}
}
}
app.component.ts
import { Component } from '@angular/core';
import{ GlobalConstants } from './common/global-constants';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Cool Title';
process = GlobalConstants.process;
}
Relevant bit of utils/util.js (line 106-116)
var debugs = {};
var debugEnvRegex = /^$/;
if (process.env.NODE_DEBUG) {
var debugEnv = process.env.NODE_DEBUG;
debugEnv = debugEnv.replace(/[|\{}()[]^$+?.]/g, '\$&')
.replace(/*/g, '.*')
.replace(/,/g, '$|^')
.toUpperCase();
debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
}
Any help is genuinely appreciated.
Always getting redirected to “/” on refresh from any route in app
So, everything works great I am redirected to homepage after login, the problem is when i refresh the page from any route i am always getting redirected to “/”, if i am in “/products” and refresh the page i m redirected to “/”
my App.js:
import Sidebar from "./components/sidebar/Sidebar";
import Topbar from "./components/topbar/Topbar";
import "./App.css";
import Home from "./pages/home/Home";
import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom";
import UserList from "./pages/userList/UserList";
import User from "./pages/user/User";
import NewUser from "./pages/newUser/NewUser";
import ProductList from "./pages/productList/ProductList";
import Product from "./pages/product/Product";
import NewProduct from "./pages/newProduct/NewProduct";
import Login from "./pages/login/Login";
import { userRequest } from "./requestMethods";
function App() {
const [admin, setAdmin] = useState(null)
useEffect(() => {
const verifyUser = async () => {
try {
const res = await userRequest.get('/verify')
setAdmin(res.data)
} catch (error) {
console.log(error)
}
}
verifyUser()
}, [])
return (
<div>
<Router>
<Switch>
<Route path="/login">
{admin ? <Redirect to="/" /> : <Login/> }
</Route>
{ admin !== null ? (
<>
<Topbar />
<div className="container">
<Sidebar />
<Route exact path="/">
<Home />
</Route>
<Route path="/users">
<UserList />
</Route>
<Route path="/user/:userId">
<User />
</Route>
<Route path="/newUser">
<NewUser />
</Route>
<Route path="/products">
<ProductList />
</Route>
<Route path="/product/:productId">
<Product />
</Route>
<Route path="/newproduct">
<NewProduct />
</Route>
</div> </>) : <Redirect to="/login"/>}
</Switch>
</Router>
</div>
);
}
export default App;
i try to use {admin !== null && (the routes here)}
and it works but when i logout the application im not redirect to the login page “/login” and still in the page that i logged out.
can someone help me please?
Webpack is not compatible with react router dom v6?
Some hours ago, i posted a question about, why my routes weren’t working in my module-federation/react application, some people tried to help me, but they couldn’t.
I was using webpack so i can use microfronteds as components with react, and with TS, but, i had a big problem with my routes.
( This is the link to the post My routing with React router dom, <Route /> not working ).
Then i said, you know what, i’ll do this with pure JS, i’m pretty sure there was a problem with ts config or something like that.
Then, after migrating everything everything to simple JS, my routes with react-router-dom are not working as before.
Is there a posibility that, the new version of react-router-dom ( https://reactrouter.com/docs/en/v6/getting-started/overview ) and webpack do not match ? This sounds weird, but i don’t see other way to figure this out.
Why this switch statement isn’t work perfectly?
const number = prompt("Enter your number");
const txt = "You result is : ";
switch (number) {
case (number >= 80 && number <= 100):
document.write(`${txt} A+`);
break;
case (number >= 70 && number <= 80):
document.write(`${txt} A gread`);
break;
case (number >= 60 && number <= 70):
document.write(`${txt} B gread`);
break;
case (number >= 50 && number <= 60):
document.write(`${txt} C gread`);
break;
case (number >= 33 && number <= 50):
document.write(`${txt} D gread`);
break;
case (number >= 0 && number <= 33):
document.write(`${txt} Field !`);
break;
case (number > 100 || number < 0):
document.write(`It's not a valid number. Please input any valid number.`);
break;
default:
document.write(`Not input any number. Please input any number .`);
break;
}
Vercel error trying to access segment route: Must use import to load ES Module
To put my problem as simply as possible, I’m using Vercel for hosting my project. Vercel allows you to easily create your own REST server by basically creating an api
folder at your project root and then you can make requests to any files in that directory which will call serverless functions that perform specific functionality via simply calling the route and filename (so if I wanted to make a request to my user.js
file, I’d simply make a request to /api/user
).
I have several different folders and files in my api
folder that all work as expected when making AJAX calls to them. When I make a request to the index.js
file in my blog folder by simply making a request to /api/blog
, everything works fine, however, when trying to make get
request to /api/blog/someId
(someId
can be any string) I get the following error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:
C:UsersMeDocumentseatsleepcode.orgapiblog[id].js
require() of ES modules is not supported.
require() of C:UsersBrettDocumentseatsleepcode.orgapiblog[id].js from
C:UsersMeAppDataRoamingnpmnode_modulesvercelnode_modules@vercelnodedistlauncher.js
is an ES module file as it is a .js file whose nearest parent package.json contains "type":
"module" which defines all .js files in that package scope as ES modules.
Instead rename [id].js to end in .cjs, change the requiring code to use import(), or remove
"type": "module" from C:UsersBrettDocumentseatsleepcode.orgpackage.json.
I simply just want the someId
portion of the /api/blog/someId
url, which I was told you access by making a file with this naming syntax [randomParameter].js
and properly route to it (/api/blog/someParameter
).
Also, my package.json
has "type":"module"
defined in it, before anyone suggests the obvious.
Recursion function in JavaScript
I have a simple recursion function that returns the sum of the first n elements of the array. I’m a little bit struggling with understanding: when the function calls itself through return return sum(arr, n-1) + arr[n-1];
what actually this sum(arr, n-1)
does as it is not added to the final sum eventually and why it’s not been calculated.
Here’s the whole function, really appreciate any explanation.
function sum(arr, n) {
if (n === 0) {return 0}
else if (n >= 1) {
return sum(arr, n-1) + arr[n-1];
}
}
Javascript function return http response as null
While console.log("result ="+req.responseText);
can output actual content, if(response == null) console.log("response null");
gets executed as well.
How can I return http response correctly?
var response = callSvc(textContent);
if(response == null) console.log("response null");
function callSvc(text){
var cleanUrl = "http://localhost:8080/api/mock";
var body={
"text":text,
"user":contentId
}
var contentId = generateContentId();
var req = new XMLHttpRequest();
req.open("POST", cleanUrl);
req.setRequestHeader("Content-Type", "application/json; charset=utf8");
var json = JSON.stringify(body);
req.send(json);
req.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
var data = JSON.parse(req.responseText);
console.log("result ="+req.responseText);
return data;
} else {
return error => {
console.error(error);
}
}
}
}
Is there a way to use a fields value in the Model to set a style attribute dynamically?
I have created a CSHTML email template file to send alerts when a specific event is about to end (i.e. sends an alert 10-minutes before end, then at 5-minutes before end, etc.). I want to highlight the type of event (since there can be more than one) by color to differentiate the messages. What I currently have is this:
<strong style="color: {event color}">@alert.event</strong> is scheduled to end: <strong>@endEasternTime
I would like to be able to set the {event color} based on the value in @alert.event, but I’m not sure that I can. I tried to create a script in the file, but I’m not sure how to get its return value into the style tag:
<script>
// Get the root element
var r = document.querySelector(':root');
// Create a function for getting a variable value
function getEventColor(event) {
// Get the styles (properties and values) for the root
var rs = getComputedStyle(r);
// Get the color associated with the event (default is the border color)
return (event === "event1"
? rs.getPropertyValue('--evt1Color')
: (event === "event2"
? rs.getPropertyValue('--evt2Color')
: (event === "event3"
? rs.getPropertyValue('--evt3Color')
: rs.getPropertyValue('--bdrColor')
)
)
);
}
</script>
Note that I have created HTML variables in the file to match up the colors to other styles in the file (such as border-color) — for space considerations and clarity, I’m not going to show that here.
Is there a way to do this? If not using the inline CSS above, can I update a class or id on the fly using something like the script method above and, if so, what’s the best way. I appreciate any help.
i need help , how can i add border and make hover for area on google map using javascript
i want to develop map like this site using laravel and javascript
how can i make border and do action when hover also display maker using google map?
thanks
Using a getter in array but getter won’t get the updated version (JAVA)
So basically I have this in one of my files:
public class Player {
private String[] PlayerWeaps;
public Player(){
PlayerWeaps = new String[5];
}
public void addWeap(int index,String name){
PlayerWeaps[index] = name;
}
public String[] getPlWeaps(){
return this.PlayerWeaps;
}
And whenever I call it on my other file as
public class GM{
private Player player;
public GM(){
this.player = new Player();
}
public void run(){
for(int i=0;i<5;i++){
System.out.println("Weapons: " + player.getPlWeaps(i)); //this guy return's null
}
}
}
I also tried assigning player.getPlWeaps first but it doesn’t work too.
note: I’m self studying JAVA so I’m really not sure if theres something I have missed
How to get key from destructed object sweetalert2
Below code pops up a modal in the view that user select one of the options and then shows the selected option, I also need the id of selected option. e.g I need to get “4” if user select “John”. I am not sure how can I get it
async function accept() {
const { value: student } = await Swal.fire({
input: 'select',
width: 260,
inputOptions: {
1: 'Peter',
2: 'Sam',
3: 'Tom',
4: 'John'
},
inputPlaceholder: 'Select student',
showCancelButton: true,
})
if (student) {
Swal.fire(`You selected: ${student}`)
console.log('Id: ' ?????)
}
}
how to send key[op]:value using axios params in js
For example –
axios.get(http://localhost:8000/api/v1/stocks/${params.id}
,
{
params: {
search: searchKeyword,
cost[gte]: 300
}
}
)
Format currency input field with dollar sign & commas
I have a revenue input field in a javascript/jquery form:
- Need a dollar sign :before
- add commas as the currency increases
I have a dollar sign showing via css, but issues centering it and ensuring the field entry point is next to it without overlapping. Unsure how to do the commas. Any suggestions or tips are welcome!
HTML:
<form id="rev-calculator">
<label for="price">Monthly Revenue</label>
<div class="fields">
<input type="number" name="price" id="price" min="0" max="10000000000" required data-type="number"> </input>
<br>
</form>
CSS:
<style>
.body {
text-align: left;
}
.fields {
margin: 0 10px 0 0;
}
.fields:before {
content: "$";
text-align: center;
position: relative;
left:30px;
}
#price {
border-radius: 5px;
margin: 15px;
padding: 10px;
color: black;
}
</style>
JS:
<script>
$('#rev-calculator').on('click', 'button', function(e) {
e.preventDefault();
var price = $("#price").val();
console.log(price);
})
</script>