I’ve recently been getting this annoying “pop-up” in vscode and I have no idea how to get rid of it. This started popping up when I began working with MySQL and now still with MongoDB and mongoose. I’ve tried disabling suggestions and even played with the setting.json as suggested by this post
Unable to turn off code suggestions in Visual Studio Code. I also disabled some of the extensions that might cause but still. Can anyone help?
Category: javascript
Category Added in a WPeMatico Campaign
Retrieving NodeJS base 64 image exif data
The frontend only sends the bese64 string to the backend. That image can be a jpeg png or an SVG. I want to get that image’s resolution, width and height from Nodejs backend. The backend only reviews the base 64 string.
Thank you!
How do i pass a function from remix loader function?
I am trying to send a function as one of the value from a remix route loader function
export const loader: LoaderFunction = async ({ request }) => {
const userId = await requireUserId(request)
const user = await getUserById(userId)
const canUserPerformAction = getUserPermissions(user)
const organisations = await Organisation.find({}).exec()
return {
organisations,
canUserPerformAction
}
}
this function always ends up being undefined when I fetch it using useLoaderData() in the default component/ frontend. Is there a better way to do this?
How can I make a request to profile API? User was redirected to the profile page after login and i want to make a get request to the user profile API
I want to make a get request to get details of the user from profile API that I have created. The profile API gives details of their user(username, email)
But when I make the request in react, I keep getting errors. I am highly confused.
The code for Login page and profile page are shown below. As well as error from the console of the browser.
import { useRef, useState, useEffect, useContext } from 'react';
import AuthContext from "./context/AuthProvider";
import axios from './api/axios';
import { useHistory } from "react-router-dom";
const LOGIN_URL = '/login/';
const Login = () => {
const { setAuth } = useContext(AuthContext);
const userRef = useRef();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
useEffect(() => {
userRef.current.focus();
}, [])
const history = useHistory()
const handleSubmit = async (e) => {
e.preventDefault();
const response = await axios.post(LOGIN_URL,
JSON.stringify({ email, password }),
{
headers: { 'Content-Type': 'application/json' },
withCredentials: true
}
);
if (response.status === 200) {
history.push("/profile");
console.log('Successfully Login');
}
console.log(response.status)
console.log(response.data)
//console.log(JSON.stringify(response?.data));
//console.log(JSON.stringify(response));
const accessToken = response.data.accessToken;
const roles = response?.data?.roles;
setAuth({ email, password, roles, accessToken });
setEmail('');
setPassword('');
}
return (
<>
<section>
<h1>Sign In</h1>
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input
type="text"
id="email"
ref={userRef}
autoComplete="off"
onChange={(e) => setEmail(e.target.value)}
value={email}
required
/>
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
onChange={(e) => setPassword(e.target.value)}
value={password}
required
/>
<button>Sign In</button>
</form>
<p>
Need an Account?<br />
<span className="line">
{/*put router link here*/}
<a href="#">Sign Up</a>
</span>
</p>
</section>
</>
)
}
export default Login
PROFILE PAGE
import React, {useState, useEffect} from 'react'
import axios from 'axios'
const Profile = () => {
const url = 'http://127.0.0.1:8000/users/profile/'
const [profile, setProfile] = useState('')
useEffect(() => {
getProfile();
}, [])
const getProfile = () => {
axios.get(`${url}`)
.then((response) => {
setProfile(response.data)
})
}
return (
<div>
<h2>Profile</h2>
<p>{profile.username}</p>
</div>
)
}
export default Profile
ERROR
[Image of the error from console]
How can I get the script name where an object of class is initiated within the class in JavaScript
I was looking for a way to get all the filenames where my class is imported and initiated an object of the class.
Is it possible to get? If yes, how?
how to call API from axios with header
I want to call the API POST method with axios, I did it with postman with header configuration like, and it return the results 
it return error when I call by axios this my script, anyone can help me what I suppose todo from the axios side ?
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
})
.then((response) => {
if (response.status !== 200) {
return res.send(respone("500", response.data.result.data))
} else {
return res.send(respone("200", response.data.result.data))
}
})
.catch((error) => {
console.log(error);
return res.send(error)
})
Using an array or the map function to improving on a nested loop performance to change/substitute cell colours in googlescript
Hi still a relative newbie here…I’ve got some nested loops which cycle through each cell in a sheet range looking for a background color and if it finds a match then the background colour is changed. Yes – I am sorry for this approach(!). Am thinking I must be able to get the background colours via an array and then apply a transformation to the array using .map(?) but have experimented and haven’t worked it out so far. Other examples on S/O don’t show a substitute approach that I have been able to apply across. Any advice/thoughts would be greatly appreciated. Thanks
function myColorFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My Sheet");
for (var y = 1; y < 70; y++){
for (var x = 1; x < 50; x++){
var bghex = ss.getRange(y,x).getBackground();
if(bghex == '#001d66') { //occasional cell colour
ss.getRange(y,x).setBackground("#027db6");
}
else if (bghex == '#00288b') { //main bkgrnd colour
ss.getRange(y,x).setBackground("#0297db");
}
else if (bghex == '#fbf025') { //yellow fill-in
ss.getRange(y,x).setBackground("#fdd201");
}
}
Logger.log('Line ' + y + ' complete');
}
}
Come posso accedere menu contestuale Chrome in modo che quando clicco Save As….poi Salva mi avvii un programma java che legge nome file in input?
Ho bisogno di capire come posso accedere all’evento contextmenu di chrome e in particolare alla scelta del tasto Save As.. e poi Save .Quando viene prenuto Save deve partire un programma in java(file.jar) che mi prenda in ingresso il nome del file da salvare cosi come viene presentato nel sotto contextmenu e lo processi in modo da salvarlo con un nome diverso di file.
how to call javascript from java using servlet
i created a register/login system using javascript and html and i connected html with java using servlet so i can get the info from the register form, so the thing i want to know is how can i call javascript from java because i want after i check the login info in java if it isn’t exist in mysql table then i want to call java script to change innerhtml to (Sorry the info you inserted doesn’t exist) or something like that but i don’t have any idea how to do it like should i use (dopost) or (doget) for it or can i call it from a normal function in java?
async await not working properly in mongo query
I have a project collection. Under the project schema have a property called tasks which is an array with the ids of the tasks. Now I am trying to write an api for singleProject, which should include the project details with a property taskDetails which will contain the detail of the tasks under the project. And for getting the task details I am using the ids which I stored in the task property under project. Below is the code I am using :
exports.getSingleProject = async (req, res) => {
req.project.logo = undefined;
await req.project.tasks.map((taskItem, index) => {
taskSchema.find({ _id: taskItem.toString() }).exec((err, task) => {
req.project.tasksDetails.push(task);
});
});
responseMessages(
res,
200,
true,
"Single project fetched successfully.",
req.project
);
};
but in the response getting taskDetails as an blank array. I guess I am using async await in wrong place. Need some help on this. Thanks in advance
Context not updating value when change routes
So I have my context set like this:
import { createContext, ReactNode, useState } from "react";
type props = {
children: ReactNode;
};
type GlobalContextType = {
name: string;
setName: (value: string) => void;
};
export const GlobalContext = createContext<GlobalContextType>(
{} as GlobalContextType
);
export const GlobalProvider = ({ children }: props) => {
const [name, setName] = useState<string>("");
return (
<GlobalContext.Provider value={{ name, setName }}>
{children}
</GlobalContext.Provider>
);
};
And I also have a input
const { name, setName } = useContext(GlobalContext);
const handleChange = (e: React.FormEvent<HTMLInputElement>): void => {
setName(e.currentTarget.value);
};
<input
placeholder="Insert a username"
onChange={handleChange}
data-testid="Login-input"
/>
If I log the “name” value that is changed through the setName it seems to work just fine
But I also have a login button that redirects to another route /home.
export const Home = () => {
const { name } = useContext(GlobalContext);
return (
<div>
<p>{name} </p>
</div>
);
};
Here, the name displays as the default value that was set up in the context, not the updated one that I changed in the input.
I tried to rewrite it but it doesn’t seem to be wrong.
Am I missing something?
Make modal undismissable javascript
I have a modal on my website, but I want to make that modal not dismissable when the progress is running, is there any way to do it? I’m using bootstrap and JQuery in case there may be things that affected by that
how to create a delete user account button in a MERN Stack application?
I created in my MERN application, a button allowing the user to delete his account.
Expected operation:
When the user clicks on the button Del, a dialog box is opened where he is asked to enter the password of the current account and then click on the delete button in order to delete the account and should send him the message User Deleted Successfully if the account was successfully deleted or an error message if not.
Current operation:
When the user clicks the Del button, it does show a dialog box where the user needs to enter the password and then click the delete button, but after clicking that button no action is performed, yet I think have well defined routes at the backend level.
my DeleteAccount file
import {
Avatar,
Button,
Card,
CardContent,
CardHeader,
CardMedia,
CircularProgress,
Dialog,
FormControl,
IconButton,
TextField,
Typography,
} from '@material-ui/core'
import { Close } from '@material-ui/icons'
import React, { useState } from 'react'
import AvartarText from '../../UI/AvartarText'
import useDeleteUser from '../../../hooks/useDeleteProfile'
function DeleteAccount({ account, userData }) {
const [dialog, setDialog] = useState(false)
const {
loading,
error,
handleDeleteUser,
handlePasswordChange ,
} = useDeleteUser(userData)
return (
<>
<Button
variant="contained"
onClick={() => setDialog(true)}
style={{
background: 'tomato',
color: '#fff',
marginBottom: '8px',
}}
>
Del
</Button>
<Dialog
open={dialog}
onClose={() => setDialog(false)}
disableBackdropClick
disableEscapeKeyDown
fullWidth
scroll="body"
maxWidth="sm"
style={{ width: '100%' }}
>
<Card style={{ width: '100%' }}>
<CardHeader
action={
<IconButton
color="primary"
onClick={() => setDialog(false)}
>
<Close />
</IconButton>
}
/>
{account.profile_pic ? (
<CardMedia
style={{
height: '150px',
width: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Avatar src={account.profile_pic} style={{ height: '200px',width:'200px' }} />
</CardMedia>
) : (
<CardMedia
style={{
height: '150px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<AvartarText
bg="teal"
text={account.name}
size="100px"
fontSize="35px"
/>
</CardMedia>
)}
<CardContent>
<div
style={{
marginTop: '20px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Typography
style={{
fontWeight: '800',
fontSize: '20px',
marginTop: '8px',
}}
>
{userData && userData.name}
</Typography>
</div>
<form onSubmit={handleDeleteUser}>
<FormControl style={{ width: '100%' }}>
<TextField
error={error && error.password ? true : false}
helperText={error && error.password ? error.password : null}
onChange={handlePasswordChange}
label="Password"
variant="outlined"
style={{ marginTop: '16px' }}
type="password"
/>
</FormControl>
<Button
type="submit"
disabled={loading}
style={{
width: '100%',
background: 'tomato',
color: '#fff',
marginTop: '16px',
}}
variant="contained"
>
{loading ? (
<CircularProgress
variant="indeterminate"
size={25}
style={{ color: '#fff' }}
/>
) : (
' Delete'
)}
</Button>
</form>
</CardContent>
</Card>
</Dialog>
</>
)
}
export default DeleteAccount
my useDeleteProfile.js :
import { useState, useContext, useEffect } from 'react'
import axios from 'axios'
import { UserContext, UIContext } from '../App'
import { useHistory } from 'react-router-dom'
import { fetchCurrentUser } from '../services/AuthService'
const url = process.env.REACT_APP_ENDPOINT
const useDeleteUser = (userData = null) => {
const { uiDispatch } = useContext(UIContext)
const { userDispatch } = useContext(UserContext)
const history = useHistory()
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const [initialState, setInitialState] = useState({
email: '',
password: '',
})
useEffect(() => {
setInitialState({ ...initialState, email: userData ? userData.email : '' })
return () => {
}
}, [])
const handlePasswordChange = (e) => {
setInitialState({ ...initialState, password: e.target.value })
setError({ ...error, password: '' })
}
async function handleDeleteUser(e) {
e.preventDefault()
setLoading(true)
try {
const { data } = await axios.delete(`${url}/api/auth/delete_profile`, initialState)
localStorage.setItem('token', JSON.stringify(data.data.token))
const me = await fetchCurrentUser()
setLoading(false)
userDispatch({ type: 'SET_CURRENT_USER', payload: me.data.user })
uiDispatch({
type: 'SET_MESSAGE',
payload: { color: 'success', display: true, text: data.message },
})
history.push('/')
} catch (err) {
setLoading(false)
console.log(err)
if (err && err.response) {
if (err.response.status === 422) {
setError({ ...err.response.data.error })
}
if (err.response.status === 400) {
uiDispatch({
type: 'SET_MESSAGE',
payload: {
color: 'error',
display: true,
text: err.response.data.error,
},
})
}
}
}
}
return {
handleDeleteUser,
handlePasswordChange ,
loading,
error,
}
}
export default useDeleteUser
SecurityAndLogin.js :
<ListItem>
<ListItemIcon>
<Lock />
</ListItemIcon>
<ListItemText
primary={<Typography>Delete my user account</Typography>}
secondary={
<Typography>
This action is irreversible. Your account will be permanently deleted
</Typography>
}
/>
<ListItemSecondaryAction>
{userState.recentAccounts.map((account) => (
<DeleteAccount account={account} />
))}
</ListItemSecondaryAction>
</ListItem>
my backend Auth.js file:
const DeleteAccount = require("../controllers/Auth/DeleteProfile")
router.delete('/delete_profile',authRequired, DeleteAccount)
my backend DeleteProfile.js :
const User = require('../../models/User')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const {JWT_SECRET,JWT_EXP} = require("../../config")
module.exports = async (req, res) => {
const { password } = req.body
let error = {}
if (!password || password.trim().length === 0) {
error.password = 'password must be required'
}
if (Object.keys(error).length) {
return res.status(422).json({ error })
}
try {
const verifyPassword = await bcrypt.compare(password, user.password)
if (!verifyPassword) {
return res.status(400).json({ error: 'password is incorrect' })
} else {
await User.deleteMany({ user: req.userId })
res.status(200).json({ message: 'User Deleted Successfully' })
}
} catch (err) {
console.log(err)
return res.status(500).json({error:"Something went wrong"})
}
}
quiz score variable isnt updating after quiz is completed
I am making a JS quiz app and have all the functionality down except for one thing. When the user is done taking the quiz the most recent score doesn’t update and will just keep displaying the first score given. This impacts the ability to display the correct score to the user and also prevents a new score being added to the leaderboard. Its a pretty big project with multiple files. So there is a lot to paste into stack.
I want to give a layout of the file structure to make it as easy to understand as possible:
The user starts at the home page which consists of index.html, style.css and script.js. To the user This is the choice of two buttons a play button and a high scores button.
The play button goes to game.html, game.css and still utilizes script.js and this is the file where the game takes place.
The highscores button utilizes highscores.html, highscores.css, and highscores.js. This page uses js dom manipulation to add highscores from local storage to put them in a list for the user to see and come back too.
The end page is what the user is presented with after the quiz is finished. this is where the user is prompted to input their name to save the score they just received and then save it to the leaderboard. This page utilize the end.html, style.css, and end.js.
I believe the problem lies with in the communication of the highscores.js/html or the end.js/html So Ill give those four files on here and please feel free to ask for others in need be. But I really appreciate the help!
In order to get a highscore you will have to go through the quiz:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Quiz Project</title>
<link rel="stylesheet" href="./assets/style.css">
</head>
<body>
<div class="container">
<div id="home" class="flex-column flex-center">
<h1>Good Luck!</h1>
<a href="./game.html" class="btn">Play</a>
<a href="./highscores.html" class="btn" id="highscores-btn">Highscores</a>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script src="./assets/script.js"></script>
Here is the HTML for the game page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Good Luck!</title>
<link rel="stylesheet" href="./assets/style.css">
<link rel="stylesheet" href="./assets/game.css">
</head>
<body>
<div class="container">
<div id="game" class="justify-center">
<div id="hud">
<div class="hud-item">
<!-- container desc -->
<p id="container-text" class="hud-prefix">
Question:
</p>
<!-- timer function -->
<div id="timer">
<h1 id="time-text">90</h1>
</div>
<!-- end of timer -->
</div>
<div class="hud-item">
<p class="hud-prefix">
Score:
</p>
<h1 class="hud-main-text" id="score">
0
</h1>
</div>
</div>
<h1 id="question">*question section placeholder*</h1>
<!-- making possible answers to given question -->
<div class="choice-container">
<p class="choice-prefix">A</p>
<p class="choice-text" data-number="1">Choice 1</p>
</div>
<!-- making possible answers to given question -->
<div class="choice-container">
<p class="choice-prefix">B</p>
<p class="choice-text" data-number="2">Choice 2</p>
</div>
<!-- making possible answers to given question -->
<div class="choice-container">
<p class="choice-prefix">C</p>
<p class="choice-text" data-number="3">Choice 3</p>
</div>
<!-- making possible answers to given question -->
<div class="choice-container">
<p class="choice-prefix">D</p>
<p class="choice-text" data-number="4">Choice 4</p>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="./assets/script.js"></script>
The js for the home screen and game screen
const question = document.getElementById('question');
const choices = Array.from($('.choice-text'));
const scoreText = document.getElementById('score');
//defining let var which values will change throughout the game
let currentQuestion = {};
let acceptingAnswers = true;
let score = 0;
let questionCounter = 0;
let availableQustions = [];
//defining list of potential questions to be called apon by currentQuestions
let questions = [
{
question: 'What types of variables can you define?',
choice1: 'var',
choice2: 'let',
choice3: 'const',
choice4: 'all of the above',
answer: '4'
},
// question 1 ^^^^
{
question: 'How would you store an item to local storage?',
choice1: 'localStorage.getItem()',
choice2: 'localStorage.setItem()',
choice3: 'localStorage.store()',
choice4: 'localStorage.setLocal()',
answer: '2'
},
// question 2 ^^^^
{
question: 'Inside which HTML tag do we write JS code?',
choice1: '<script>',
choice2: '<jscript>',
choice3: '<scripting>',
choice4: '<javascript>',
answer: '1'
},
// question 3 ^^^^
{
question: 'What is the correct JavaScript syntax to change the content of a <p>
in HTML document?',
choice1: 'document.getElement("p").innerHTML = "Hello World"',
choice2: '(p).innerHTML = "Hello World"',
choice3: 'getElement("p").value = "Hello World"',
choice4: 'document("p").innerHTML = "Hello World"',
answer: '1'
},
// question 4 ^^^^
{
question: 'How would you write "Hello World" in an alert box?',
choice1: 'msgBox("Hello World");',
choice2: 'message("Hello World");',
choice3: 'alertBox("Hello World");',
choice4: 'alert("Hello World");',
answer: '4'
},
// question 5 ^^^^
{
question: 'How do you create a function?',
choice1: 'function:myFunction()',
choice2: 'function = myFunction()',
choice3: 'function myFunction()',
choice4: 'var function.value() = myFunction()',
answer: '3'
},
// question 6 ^^^^
{
question: 'How do you write an "if" statement?',
choice1: 'if = i == 5',
choice2: 'if (i == 5)',
choice3: 'if i == 5 then',
choice4: 'if i = 5',
answer: '2'
},
// question 7 ^^^^
{
question: 'How do you make a comment in JavaScript?',
choice1: '/*example*/',
choice2: '<!--example-->',
choice3: '//example',
choice4: '`example`',
answer: '3'
},
// question 8 ^^^^
{
question: 'What is the correct way to make an array?',
choice1: 'var colors = ["red", "green", "blue"]',
choice2: 'var colors = ("red", "green", "blue")',
choice3: 'var colors = {"red", "green", "blue"}',
choice4: 'var colors = "red", "green", "blue"',
answer: '1'
},
// question 9 ^^^^
{
question: 'JavaScript is a ____-side programming language.',
choice1: 'Client',
choice2: 'Server',
choice3: 'Both',
choice4: 'None',
answer: '3'
},
// question 10 ^^^^
]
//start game functionality and needed var
const SCORE_POINTS = 100;
const MAX_QUESTIONS = 10;
startGame = () => {
questionCounter = 0;
score = 0;
availableQustions = [...questions];
getNewQuestion();
}
//get new question function supplies new q when previous gets answered
getNewQuestion = () => {
if(availableQustions.length === 0 || questionCounter > MAX_QUESTIONS) {
localStorage.setItem('mostRecentScore', score)
return window.location.assign('./end.html')
}
questionCounter++
//making random question appear
const questionIndex = Math.floor(Math.random() * availableQustions.length)
currentQuestion = availableQustions[questionIndex]
question.innerText = currentQuestion.question
//was originally choices.array.forEach
choices.forEach((choice)=> {
const number = choice.dataset['number'];
choice.innerText = currentQuestion['choice' + number];
});
availableQustions.splice(questionIndex, 1);
acceptingAnswers = true;
}
choices.forEach(choice => {
choice.addEventListener('click', e => {
if (!acceptingAnswers) return
acceptingAnswers = false
const selectedChoice = e.target
const selectedAnswer = selectedChoice.dataset['number']
let classToApply = selectedAnswer == currentQuestion.answer ? 'correct' :
'incorrect'
//if answer is correct add 100 to score
if (classToApply === 'correct') {
incrementScore(SCORE_POINTS)
} else {
//timer time will be subtracted by 10 if question is answered incorrectly
timerSec -= 10;
}
selectedChoice.parentElement.classList.add(classToApply)
setTimeout(() => {
selectedChoice.parentElement.classList.remove(classToApply)
getNewQuestion();
}, 1000)
})
});
//increment score funt and calling start game
incrementScore = num => {
score +=num
scoreText.innerText = score
}
startGame();
//timer funct for 90 sec
var timerSec = 90;
var timerText = document.getElementById('time-text')
var timer;
timer = setInterval(function() {
timerSec--;
timerText.textContent = timerSec
//if timer is less than or = to 0 the game will end
if (timerSec <= 0) {
clearInterval(timer);
return window.location.assign('./end.html');
//if there is no available q's and the timer is greater than 0 game will end
}if (availableQustions === 0 && timerSec > 0) {
clearInterval(timer);
return window.location.assign('./end.html');
}
},1000)
As A reminder; the sections above are not the cause for concern I just want ya’ll to e able to go through the full functionality of the app. As it stands thats the only way to create a mostRecentScore variable and store it to local. The code below are the HTML of the js files associated with the prolem.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Good Job!</title>
<link rel="stylesheet" href="./assets/style.css">
</head>
<body>
<div class="container">
<div id="end" class="flex-center flex-column">
<h1 id="final-score">0</h1>
<form action="" id="end-form-container">
<h2 id="end-text">Enter your name below in order to save your score.
</h2>
<input type="text" name="name" id="username" placeholder="Enter your
name">
<button class="btn" id="save-score-btn" type="submit"
onclick="saveHighScore(event)" >Save</button>
</form>
<a href="./game.html" class="btn">Play Again?</a>
<a href="./index.html" class="btn">Home</a>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script src="./assets/end.js"></script>
</html>
This is the highscores section:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Highscores</title>
<link rel="stylesheet" href="./assets/style.css">
<link rel="stylesheet" href="./assets/highscores.css">
</head>
<body>
<div class="container">
<div class="container">
<div id="highscores" class="flex-center flex-column">
<h1 id="final-score">Leaderboard</h1>
<ul id="high-scores-list"></ul>
<a href="./index.html" class="btn">Go Home</a>
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script src="./assets/highscores.js"></script>
</html>
Now for the part that is causing all of my headaches. This is the end.js
const username = document.querySelector('#username')
const saveScoreBtn = document.querySelector('#save-score-btn')
const finalScore = document.querySelector('#final-score')
const mostRecentScore = localStorage.getItem('mostRecentScore')
const highScores = JSON.parse(localStorage.getItem('highScores')) || []
const MAX_HIGH_SCORES = 1000
finalScore.innerHTML = mostRecentScore
saveHighScore = e => {
e.preventDefault()
const score = {
score: mostRecentScore,
name: username.value
}
highScores.push(score)
highScores.sort((a,b) => {
return b.score - a.score
})
highScores.splice(10)
localStorage.setItem('highScores', JSON.stringify(highScores))
window.location.assign('./highscores.html')
}
And the highscores.js
const highScoresList = document.querySelector('#high-scores-list')
const highScores = JSON.parse(localStorage.getItem('highScores')) || []
highScoresList.innerHTML = highScores.map(score => {
return `<li class="high-score">${score.name} - ${score.score}</li>`
}).join('')
Sorry for the very long explanation for what is hopefully a simple fix. Let me know if any edits are needed or if there is follow up questions I can answer.
Thanks for all the potential help!
How to find numbers and remove them from a multidimensional array?
I’m trying to create a Bingo game to play with my family and I would like to know what is the best way to remove numbers that have been called and then create another array with the tickets that is empty – so I know they have already win.
So far I made this array (I reduced it to make easier to understand):
var tickets = [
['T1',1,2,8,10,23,18,44],
['T2',2,3,3,6,45,12,55],
['T3',4,7,10,42,55,45,60],
['T4',3,5,3,6,55,68,85],
['T5',1,4,3,6,66,74,80],
];
All the other part of bingo is done, I just need to realize how can I know the tickets that have finished already to make easier to validate the winners.

