Actually the thing i want is play a sound from texbox’s value
Ex: user writed 01:05:08 the sound start playing from 01:05:08 moment.
This is what i want.
Can anyone help me?
(Note: İ don’t want use jquery)
Category: javascript
Category Added in a WPeMatico Campaign
How to add pseudo elements to range slider thumb
When I have three files
test1.html
<script src="main.js" defer></script>
...
<div class="divOne"></div>
test2.html
<script src="main.js" defer></script>
...
<div class="divTwo"></div>
main.js
document.querySelectorAll('.divOne');
document.querySelectorAll('.divTwo');
Then I would get an error in the test1.html file that divTwo cannot be found.
In test2.html I would get the error that divOne cannot be found.
How can I make JavaScript code optimal that I can include my JavaScript file for reusable components on any page, but if something doesn’t exist because I don’t use it in the file, nothing should happen?
Highlight div element by darkening everything around it
I want to highlite a relativ positioned div element from a layer below, by making everything around it darker.
What I have tried:
- Copy the position of the original element, and the element itself and then insert that element at the copied position
- Construct the darker layer out of 4 rectangles so that this creates a negative rectangle, where the heart element I want to highlight shines through (picture 2)
Has anyone a really smart idea of how to achieve this? Both solutions, kind of work, but are really prone to errors.
String inputs are getting outputted as hexadecimals
in Javascript I have a string called inputs which stores the value 0xff
const inputs = 0xff
However this is getting outputted like a number, 255 is being outputted if I print the variable. Is there a way to stop a string being converted to a hexadecimal number, or is there a way to convert from a hexadecimal number back again to a string.
Thank you for any help.
How to get this equalize image filter effect with javascript
How to call a function everytime my route changes? using useEffect hook
I’m working on a chat application and I want to make it like whenever user opens a chat it should show the latest chat.
So to do that I made a function scrollToBottom() that scroll to the bottom of the chat after 1 second, but I want to make it run, everytime the route changes. I tried placing router.query.id in useEffect dependency but it runs on every second automatically.
useEffect(() => {
setTimeout(() => {
scrollToBottom();
}, 1000);
}, [router.query.id]);
So basically I want this useEffect to run only when router.query.id changes, that is only when the URL changes. How can I do that? Help would be appreciated.
React Calling function from another file and useEffect
Hello I am trying to render the updated stuff from the database whenever the update is invoked to the database. I found this solution but right now my “add” method is not in the same file as the “fetch” method like in the linked question. I tried the below but it still isn’t working:
file 1: (the return method will render the UploadedImages by mapping them)
const [UploadedImages,setUploadedImages] = useState([])
const fetchUserAllPhotos = async () => {
const res = await client.get('/get-photos')
setUploadedImages(res.data.photoList)
}
useEffect(()=>{
fetchUserAllPhotos()
},[])
file 2:
import {fetchUserAllPhotos} from './Gallery/AllPhotos';
const addNewPhoto = async () => {
if (success) {
await fetchUserAllPhotos()
}
}
However inside the file 1’s return (render) method it is not giving the updated result whenever a new photos is added (I need to sign out and sign back in in order to see the change). How can I go about solving it?
How to implement a forward ref in React0.14?
I want to get the ref of the children’s component.The nested relationship between the components is shown below:
<Demo1 /> ---> <Demo2 /> ---> <Demo3 />
how to get the ref of Demo3 in Demo1?
Express JS direct redirecting index page results in blank page
I implemented a simple middleware “checkMaintenanceMode”, which redirects each page to a static maintenance / under construction page.
const initStaticPages = (router) => {
router.use('/main', checkMaintenanceMode, requireAccess, express.static('public'))
router.use('/logout?reason=timeout', checkMaintenanceMode, express.static('public'))
router.use('/logout', checkMaintenanceMode, express.static('public'))
router.use('/login', checkMaintenanceMode, express.static('public'))
router.use('/requestHistory', checkMaintenanceMode, requireAccess, express.static('public'))
router.use('/recurringRequest', checkMaintenanceMode, requireAccess, express.static('public'))
router.use('/maintenance', express.static('public'))
router.use('/', checkMaintenanceMode, express.static('public'))
const checkMaintenanceMode = (req, res, next) => {
if (maintenanceMode) {
res.redirect('/maintenance/')
} else {
next()
}
}
When adding the middleware to the “/” route, loading the index page results in a blank page with error message: Expected a JavaScript module script but the server responded with a MIME type of “text/html”. Strict MIME type checking is enforced for module scripts per HTML spec.
Any idea what could be the reason for that?
When using router.use(‘/’, express.static(‘public’)), it works, but I also want to redirect directly when a user opens the page.
Trying to setup a new welcome.js
const Discord = require('discord.js')
const bot = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_MEMBERS"]})
const config = require('./botconfig.json')
const prefix = '...';
const welcome = require("./welcome");
const Welcome = require("discord-welcome");
const client = new Discord.Client({
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MEMBERS,
],
});
bot.on('ready', async () => {
console.log(`${bot.user.username} is online and in ${bot.guilds.cache.size} server!`)
})
// START OF WELCOME BOT
bot.on('guildMemberAdd', async member => {
client.channels.cache.get('ChannelHere')
let embed = new Discord.MessageEmbed()
.setTitle('TESTING EMBED')
.setDescription('TITLE LAUNCHED...')
.setColor("#ffd8e3")
channel.send(`please welcome ${member} to the server!`, embed)
//client.channels.get("775086826154229840").send(`please welcome ${member} to the server!`, embed)
//msg.channel.send(`please welcome ${member} to the server!`, embed)
});
// END OF WELCOME BOT
bot.login(config.token)
Whenever a user joins, it failes. It worked on the last server but not now?
Any help or indication that something is wrong would be much appreciated.
I am new to this so sorry if bad
Error is thrown and caught in the backend but the fronted React does not catch the error
I was doing a course in MERN Stack and during that I encountered a problem. For one form submission page the backend error handling was done in this way:
router.put('/education' , [auth ,
check('school','School is required').notEmpty(),
check('degree','Degree is required').notEmpty(),
check('fieldofstudy','Field of Study is required').notEmpty(),
check('from','From date is required').notEmpty()
],
async (req,res)=>{
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.json({ errors:errors.array()});
}
const {
school,
degree,
fieldofstudy,
from,
to,
current,
description
} = req.body;
const newEdu = {
school,
degree,
fieldofstudy,
from,
to,
current,
description
}
try {
const profile = await Profile.findOne({ user: req.user.id })
if(profile) console.log('profile found req body is', req.body )
profile.education.unshift(req.body);
console.log('unshifted')
await profile.save();
res.json({ profile })
} catch (err) {
res.status(500).send("Server Error");
}
})
Now if I use Postman to to send some blank raw data as the inputs of the form, It does give back the errors that it is supposed to.
The frontend code used to make this request looks something like this:
export const addEducation = (formData, navigate )=> async dispatch => {
try {
const res = axios.put('http://localhost:5000/api/profile/education',formData)
dispatch({
type: UPDATE_PROFILE,
payload: res.data
});
dispatch(setAlert('Education Added', 'success'))
navigate('/dashboard')
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
dispatch({
type: PROFILE_ERROR,
});
}
}
The formData is sent through the form page upon Submission of the form.
What this code does is even if all the fields are empty, it just submits the form and sets the alert to ‘Education Added’ and navigates to ‘/dashboard’. The database shows no entry of a empty Education field whatsoever. Also the input tags in the form do not have ‘required’ attribute set.
Why isn’t it catching the errors and setting alerts for them?
I am fairly new to MERN so any help will be greatly appreciated!
Make pSortableColumn NOT change state when inner element is clicked
I have a setup like this:
<th pSortableColumn="something">
<span>text</span>
</th>
How do I prevent the th element from changing state when I click on “text”? I don’t want it to be selected and I don’t want it to sort.
react doesn’t render the components on build
In the dev mode, everything worked as expected, but when I build the project the components didn’t mount
this is my index.js
ReactDOM.render(
<BrowserRouter>
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
</BrowserRouter>,
document.getElementById("root")
);
this is app.js
function App() {
return (
<div className="App">
<GlobalStateInitialSetters />
<Routes>
<Route
path="/"
element={
<>
<Main />
<Footer />
</>
}
/>
<Route path="/favorites" element={<Favorites />} />
</Routes>
</div>
);
}
Estou fazendo um projeto de imc usando html e js mas ele não funciona [closed]
Alguém poderia por favor me ajudar a descobrir o por que do meu código não estar retornando resultado algum? Esse é um trabalho que estou fazendo para a faculdade sobre IMC. Deveria pedir pelo nome, peso, altura, fazer o calculo e retornar o valor do imc do usuário assim como a categoria aonde ele se enquadra.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<html lang="pt-br">
<title> Indice de massa corporal </title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<form id="form1">
<label> Nome </label>
<input type="text" id="nome" placeholder="nome">
<label> Qual sua altura? </label>
<input type="int" id="altura" placeholder="altura">
<label> Qual seu peso? </label>
<input type="int" id="peso" placeholder="peso">
<input type="submit" value="enviar" onclick="IMC">
<script type="text/javascript">
function IMC() {
var altura = document.getElementById("altura").value;
var peso = document.getElementById("peso").value;
var m = peso / altura * altura;
parseFloat(altura);
parseFloat(peso);
if (m < 16){
var i = 'Baixo peso muito grave';
} else if (m > 16 && m < 16.99) {
var i = 'Baixo peso grave';
} else if (m > 17 && m < 18.49) {
var i = 'Baixo peso';
} else if (m > 18.50 && m < 24.99) {
var i = 'Peso normal';
} else if (m > 24 && m < 29.99) {
var i = 'Sobrepeso';
} else if (m > 30 && m < 34.99) {
var i = 'Obesidade de primeiro grau';
} else if (m > 35 && m < 39.99) {
var i = 'Obesidade de segundo grau';
} else if (m > 40) {
var i = 'Obesidade de terceiro grau';
}
document.write(nome + " possui indice de massa corporal igual a " + m + "sendo classificado como" + i);
}
</script>
</form>
</div>
</body>
</html>
Eu digito os valores no input mas a página apenas recarrega
Why is WebStorm not showing suggestions for anode.parentNode.classList? In fact it is underlining it as wrong
So I have noticed sometimes WebStorm does not show proper suggestions with JavaScript and even underlines valid code as wrong. In this case, the missed suggestion happens with this code:
document.addEventListener(“DOMContentLoaded”, () => {
//Get form and required fields
const form = document.querySelector("#mainForm");
const required = document.querySelectorAll(".required");
form.addEventListener('submit', validateForm); //Add Listener to submit form
function validateForm(e) {
//Check if title is blank
if (required[0].value === "" || required[0].value == null) {
required[0].parentNode.classList.add("highlight"); //Add to parent
required[0].classList.add("highlight"); //Add to child
e.preventDefault();
}
//Check if checkbox is checked
if (!required[2].checked || required[2].value == null) {
required[2].parentNode.classList.add("highlight"); //Highlight parent (box)
e.preventDefault();
}
}
});
The problem is in ” required[0].parentNode.classList.add(“highlight”) ” WebStorm underlines .classlist as wrong. In fact when I type required[0].parentNode. it does not suggest classList as an option. I checked it with VS Code and VS Code does make that suggestion. Does anybody know why and how to fix it, so that Webstorm gives me correct suggestions in this case?
I was expecting to show .classList as an option as VS Code does but it is not doing it. I like Webstorm a lot more, but this has happenede before in the past, making me think I am doing something wrong.



