Category: javascript
Category Added in a WPeMatico Campaign
How can I make the hands of the clock rotate? (p5.js / javascript)
How can I make the hands of the clock rotate? By me only the whole picture rotates. The hands are in the same class as the exterior of the clocks. The clocks move across the image. Thank you.
Here is a part of the code:
function startViz() {
for (let i = 0; i < 5; i++) {
bubbles.push(new Bubble());
}
}
function drawViz() {
ground.background(30);
for (let b of bubbles) {
b.update();
b.show();
b.show1();
}
}
class Bubble {
constructor() {
this.r = random(50, 80);
this.x = random(this.r, width - this.r);
this.y = random(this.r, height - this.r);
this.vx = random(-1 * (w*0.005), 3 * (w*0.005));
this.vy = random(-1 * (w*0.005), 3 * (w*0.005));
this.color = color(random(255), random(255), random(255));
}
show() {
ground.noFill();
ground.stroke(255);
ground.fill(this.color);
ground.strokeWeight(3);
ground.circle(this.x, this.y, this.r * 2 * (w*0.005));
}
show1() {
ground.line(this.x, this.y, this.x + this.r / 2 * (w*0.005), this.y + this.r / 2 * (w*0.005));
ground.line(this.x, this.y, this.x - this.r / 2 * (w*0.005), this.y + this.r / 2 * (w*0.005));
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.x > width - this.r || this.x < this.r) {
this.vx *= -1;
}
if (this.y > height - this.r || this.y < this.r) {
this.vy *= -1;
}
}
}
Unable to override url link text using appendChild textNode
I have a page (one of many) each with an html table of 3 cells of headings (dimension, height, width) and 3 cells of values eg ‘100 by 50’, 100, 50
I aim to create links at the base of the page to url examples with dimensions similar to these, slightly larger, slightly smaller.
I collect the numbers from the dynamically generated table and add or subtract to get the new values using:
`
var $ = jQuery;
$(function () {
$('#table_1 tr').each(function() {
var heightAdd1 = parseInt($(this).find("td").eq(1).html())+1;
var heightLess1 = parseInt($(this).find("td").eq(1).html())-1;
var widthAdd1 = parseInt($(this).find("td").eq(2).html())+1;
var widthLess1 = parseInt($(this).find("td").eq(2).html())-1;
` etc.
I then place these into a new url link using:
$("a#heightAdd1widthAdd1").attr("href", "https://www.example.com/" + heightAdd1 + "-by-" + widthAdd1);
I want the link texts to show on the page as e.g. ‘101-by-51′ ’99-by-49’ with whatever variation of numbers get generated.
On the html page I have `
<a id="heightAdd1widthAdd1" href="#">height+1 width+1</a><br>
<a id="heightLess1widthLess1" href="#">height-1 width-1</a>
I try to overwrite this fixed text using:
let textNode = document.createTextNode(heightAdd1 + "-by-" + widthAdd1);
document.getElementById("heightAdd1widthAdd1").innerHTML = document.body.appendChild(textNode);
` but the output I get on the page overwrites it to only show ‘[object Text]’ which still has the correct url link.
How can I get the url link text to read instead of ‘[object Text]’, e.g. ‘101-by-51’? The fiddle example is here https://jsfiddle.net/qm9cLs0o/ if you delete lines 33 and 34 the original text in the html shows again. Hovering over the links show the urls are correct.
Javascript passing string with variables in the string, How do I do this?
Here’s the line of code calling a function and passing a string with JS variables in it.
const min = 3,
max = 25;
showError(name, 'Name must be between ${min} and ${max} characters.');
It sends the string fine, but does not replace the ${min} and ${max} with the actual variable values.
JS regex pathname match
i’m a bit lost about regex. What I want is to create is a simple check and match a path. (regex noob)
To clarify;
The application can have sub directories
* Directory
/
/dashboard/modules
/modules/acounting/
/modules/acounting/stats
/modules/invoicing/
/modules/invoicing/invoices
What I want to accomplish is to match against everything from first forward slash to slash except the pages.
* Directory
/
/dashboard/
/modules/acounting/
/modules/invoicing/
Tried //([^/]+)/[^/]*$/)
const url = window.location;
url.pathname.match(//([^/]+)/[^/]*$/)
It creates a array. Regex help appreciated
My node.js gives me error and I dont understand what’s the problem
This is the error please help me. I tried to npm install @discord-api-types/v9 but nothing changed. I am trying to create a discord bot but when I type node index.js to terminal it keeps giving me error.
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module '@discord-api-types/v9'
Require stack:
- C:UsersMONSTERDesktopRayman Musicindex.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:UsersMONSTERDesktopRayman Musicindex.js:4:20)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'C:\Users\MONSTER\Desktop\Rayman Music\index.js' ]
}```
How to logout a deleted user that is currently logged in, in JavaScript?
I have a list of users that i can delete from once i log in with any of the users. I want to remove the currentAccount from sessionStorage if the currently logged in user deletes himself. I am using an id to delete a user. This is how i have defined it so far.
function deleteUser(id) {
let form = document.querySelector("#queryForm");
let formData = new FormData(form);
formData.append("action", DELETE);
formData.append("ids", id);
sendPost("/SMS/user", formData2Url(formData), handleDelete);
let currentAccount = sessionStorage.getItem("currentAccount");
if (id === currentAccount.id) {
sessionStorage.removeItem(currentAccount);
}
console.log(id);
console.log(currentAccount);
console.log(Object.values(currentAccount)[0]);
}
How to append JSON object to existing JSON object in json file in react.js
I am trying to save data in data.json file in React.js.
I want accept data from user and add more data at the end of already existing data in json file.
I want to append another JSON object with existing. How can I do it?
data.json file looks like:
{
"Riya":{
"id": 1,
"title": "Learn backbone",
"Description": [
[1,2,3,4],[5,6,7,8],[1,2,4,5]
],
"date": new Date().getTime()
},
"Khushi": {
"id": 2,
"title": "Learn hippop",
"Description": [
[1,2,3,4],[5,6,7,8],[1,2,4,5]
],
"date": new Date().getTime()
}
}
New data.json file should be like this:
{
"Riya":{
"id": 1,
"title": "Learn backbone",
"Description": [
[1,2,3,4],[5,6,7,8],[1,2,4,5]
],
"date": new Date().getTime()
},
"Khushi": {
"id": 2,
"title": "Learn hippop",
"Description": [
[1,2,3,4],[5,6,7,8],[1,2,4,5]
],
"date": new Date().getTime()
},
"Prachi": {
"id": 3,
"title": "Learn music",
"Description": [
[1,2,3,4],[1,6,7,8],[1,2,4,5]
],
"date": new Date().getTime()
}
}
I’m trying to deploy a function for the notifications of my application (Firebase function) I don’t understand how to solve the error
I’m trying to deploy a function to send notifications for my chat application. I get this error but I can’t understand where the error comes from.
Could you help me to understand where the error comes from please?
Is this a problem with my code in the index.js file?
Can you help me ?
index.js :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.notifyNewMessage = functions.firestore
.document('notifications/{uId}/messages/{messageId}')
.onCreate( async (docSnapshot, context) => {
//************************************Obtener datos de la notificacion
const messageNotification = docSnapshot.data();
////////////extraemos los datos
const uidAuthor = messageNotification['uidAuthor'];
const uidReceiver = messageNotification['uidReceiver'];
const messages = messageNotification['message'];
const typeNotification = messageNotification['type'];
//************************************DECLARAR PROMESAS
const getAuthorData = admin.firestore().doc('users/' + uidAuthor).get();
const getReceiverData = admin.firestore().doc('users/' + uidReceiver).get();
//************************************
const results = await Promise.all([getAuthorData, getReceiverData]);
//************************************
const author = results[0];
const receiver = results[1];
//************************************GET DATA USER AUTHOR
const name = author.get('name');
//************************************GET DATA USER RECEIVER
const tokenNotification = receiver.get('tokenNotification');
//console.log("Datos recogidos USER TO NOTIFY:TOKENS " + tokens);
//////////////////////////////////NOTIFICATION DATA
payload = {
data: {
typeNotif: typeNotification.toString(),
userName: name,
userID: uidAuthor,
message: messages
}
};
admin.messaging().sendToDevice(tokenNotification, payload)
.then(function(response) {
return response;
})
.catch(function(error) {
return error;
});
//////////////////////////////////
});
firebase.js:
{
"functions": {
"predeploy": [
"npm --prefix functions run lint"
]
}
}
JsSIP How to detect call transfer successfullly
A holding session with B and calling on session with C. A transfer B to C by implementing code below. How to get info of B in C, i tried listening ua.on('newMessage', cb) and adding ua.sendMessage(currentSession?.remote_identity.uri, 'dataOfB') in A but ua.on('newMessage', cb) only fired in A.
How to C detect call transfered successfully or get message from A. Thanks all!
replaces: currentSession,
mediaConstraints: { audio: true, video: false },
pcConfig: {
rtcpMuxPolicy: 'negotiate',
},
};
holdSession?.refer(currentSession?.remote_identity.uri, options);
currentSession?.terminate();
holdSession?.terminate();
Regular Expression
I have a question about regular expressions.
I want to check in a string if the closing bracket ‘]’ occurs exactly x times.
So in this example the bracket occurs exactly 5 times.
"[ 357","-0.9","99","16 ] ] ] ] ]"
I have tried this so far:
var reg = /]{5}/;
but lines containing more than 5 brackets also appear here.
What do I need to change in the expression?
Thanks in advance!
Insert and delete checkbox using MySQL and PHP. Use chcekbox like favorites button
I’m trying to use checkbox like favorites button where user can like some articles and then see his favorites articles on web page. And when he no longer likes it, he just unchecks it. Is it possible to do it using PHP, MySQL and JavaScript?
How do I fix VM457:236 Unexpected text node: . A text node cannot be a child of a ?
in my react page I get these 2 errors :
index.js:63/ VM457:236 Unexpected text node: . A text node cannot be a child of a <View>.
(I guess this is this file which generates this error since it’s the only one where I use AreaInputView)
import { Tab, Tabs as TabsComponent, TabList, TabPanel } from "react-tabs";
import { SafeAreaView, TextInput } from "react-native";
import { EditorState } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
...
const TabContent = ({ name, typeProof }) => {
...
const [editorState, setEditorState] = useState(() =>
EditorState.createEmpty()
);
return (
<>
<p> Question: <i>{name}</i></p>
<Editor
editorState={editorState}
onEditorStateChange={setEditorState}
...
toolbar={{options: [...]}}
/>
<p>Comment</p>
<SafeAreaView>
<TextInput
onChangeText={(value) => setComment(value)}
value={comment}
/>
</SafeAreaView>
</>
);
};
export default function Tabs({ data }) {
return (
<TabsComponent forceRenderTabPanel>
....
);
}
keyframes creating issue when using with jQuery
I am trying to create bubble and also bubble burst on click.I am using two keyframes, One for bubbling, and other is when click on bubble.
Problem is when I click on bubble the effect is showing on wrong areas. Here is my code sample. i can’t understand where is the issue is
because of two keyframes timing is wrong. how to adjust click effect where the bubble is exactly click.
$('.bubbles li').on('click',mouseremove, function () {
const thisBubble = $(this);
thisBubble.addClass('bubble-pop');
setTimeout(() => {
thisBubble.hide();
mouseremove(thisBubble);
}, 500);
});
function mouseremove(thisBubble) {
thisBubble.removeClass('bubble-pop');
setTimeout(() => {
thisBubble.show();
}, 500);
}
.bubbles {
position: absolute;
top: 0;
left: 0;
width:100%;
height:100%;
z-index: 0;
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
.bubbles li {
position: absolute;
list-style: none;
display: block;
background-image: url('https://www.fundacioarcadi.com/wp-content/uploads/2019/09/bombolla-01.png');
background-size: 20px;
bottom: -100px;
-webkit-animation: square 40s infinite ;
animation: square 40s infinite ;
-webkit-transition-timing-function: linear;
transition-timing-function: linear;
}
li{
background-image: url("https://www.fundacioarcadi.com/wp-content/uploads/2019/09/bombolla-01.png");
background-size: cover !important;
}
.bubbles li:nth-child(1) {
width: 250px;
height: 250px;
left: 10%;
}
.bubbles li:nth-child(2) {
width: 200px;
height: 200px;
left: 40%;
-webkit-animation-delay: 2s;
animation-delay: 2s;
-webkit-animation-duration: 60s;
animation-duration: 60s;
}
.bubbles li:nth-child(3) {
width: 100px;
height: 100px;
left: 60%;
-webkit-animation-delay: 4s;
animation-delay: 4s;
-webkit-animation-duration: 60s;
animation-duration: 60s;
}
.bubbles li:nth-child(4) {
width: 160px;
height: 160px;
left: 80%;
-webkit-animation-delay: 1s;
animation-delay: 1s;
-webkit-animation-duration: 45s;
animation-duration: 45s;
}
.bubbles li:nth-child(5) {
width: 100px;
height: 100px;
left: 50%;
-webkit-animation-delay: 20s;
animation-delay: 15s;
-webkit-animation-duration: 35s;
animation-duration: 35s;
}
.bubbles li:nth-child(6) {
width: 100px;
height: 100px;
left: 10%;
-webkit-animation-delay: 20s;
animation-delay: 15s;
-webkit-animation-duration: 65s;
animation-duration: 65s;
}
.bubbles li:nth-child(7) {
width: 100px;
height: 100px;
left: 90%;
-webkit-animation-delay: 20s;
animation-delay: 45s;
-webkit-animation-duration: 30s;
animation-duration: 30s;
}
@-webkit-keyframes square {
0% {
-webkit-transform: translateY(0);
transform: translateY(0);
}
100% {
-webkit-transform: translateY(-1080px);
transform: translateY(-1080px);
}
}
@keyframes square {
0% {
-webkit-transform: translateY(0);
transform: translateY(0);
}
100% {
-webkit-transform: translateY(-1080px) rotate(180deg);
transform: translateY(-1080px) rotate(180deg);
}
}
.bubble-pop {
-webkit-animation: bubblePop 0.4s ease !important;
-moz-animation: bubblePop 0.4s ease !important;
animation: bubblePop 0.4s ease !important;
opacity: 0 !important;
}
@-webkit-keyframes bubblePop {
0% {
-webkit-transform: scale(0.2);
opacity: 1;
}
20% {
-webkit-transform: scale(0);
opacity: 0.6;
}
100% {
-webkit-transform: scale(0.2);
opacity: 0;
}
}
@-moz-keyframes bubblePop {
0% {
-moz-transform: scale(0.2);
opacity: 1;
}
20% {
-moz-transform: scale(0);
opacity: 0.6;
}
100% {
-moz-transform: scale(0.2);
opacity: 0;
}
}
@keyframes bubblePop {
0% {
transform: scale(0.2);
opacity: 1;
}
20% {
transform: scale(0);
opacity: 0.6;
}
100% {
transform: scale(0.2);
opacity: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Fixing Uncaught TypeError: Cannot read properties of undefined (reading ‘style’)
I’m trying to make a slideshow in my react app. I’m using the below function for the slideshow.
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("diabetes-day");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {
myIndex = 1
}
x[myIndex - 1].style.display = "block";
setTimeout(carousel, 5000); // Change image every 5 seconds
}
<div className="slideshow-container">
<div className="diabetes-news">
<img className="diabetes-day" src={DiabetesDay}/>
<img className="diabetes-day" src={Symptoms}/>
<img className="diabetes-day" src={Managing}/>
</div>
</div>
When I run the code the slideshow works. But as soon as I refresh the page all the contents in the page disappears and I get the following error in my console.
I’m not quite sure why it stops working once the page is refreshed. It would be great if someone could guide me on how to fix this.
