Category: javascript
Category Added in a WPeMatico Campaign
How to select specific value in a Query in HTML
I need to know how to select a specific value in a form of a query.
Under the Content.join('');, I need to select like 2 values which is the Hello and Lorem ipsum… then Hi and Nullam fringilla…, and so on.
Sorry, kinda new to this stuff as well.
<script>
var Count = 0;
var title = document.getElementById("getTitle");
var desc = document.getElementById("getDescription");
var Content = [
["Option1", "Hello", "Lorem ipsum dolor sit amet"],
["Option2", "Hi", "Nullam fringilla imperdiet eleifend"],
["Option3", "Greetings", "Cras dapibus ipsum a consequat tincidunt"]];
function previewImg(DibsSrc){
document.getElementById("Dibs").src =DibsSrc.src;
Content[Count][0] = DibsSrc.id;
title.innerhtml = Content.join('');
desc.innerhtml = Content.join('');
}
</script>
cy.intercept randomly not work when “delay” is set
I use cy.intercept to mock an api.
But I can’t understand why the requests are not always intercepted by cy.intercept. The failure is random.
Here is my intercept function
cy.intercept('GET', '**/api/search?searchValue=**', {fixture: 'searchFixutre.json', delay: 500}).as('api');
Randomly, when this route is called several times quickly, Cypress does not intercept the request and it is sent directly to the api server.
Note that this problem does not occur when I delete the “delay” property
cy.intercept('GET', '**/api/search?searchValue=**', {fixture: 'searchFixutre.json'}).as('api');
Monaco-Editor increase suggestion width using css or props
ReactJS push to state array replaces every exisitng value in array
I want to push an 2d array into the end of a state. But somehow, when i log the state every time it changes with a useEffect, i replaces every existing array with the new one.
The variable “position” is my 2d array, also a state. Might this cause any reference problems?
I have no idea and im starting to lose my mind about this…
const [positionList, setPositionList] = useState([]);
useEffect(() => {
const updatePosition = [...positionList, position]
setPositionList(updatePosition);
}, [playerTurn])
expected output (or what i want)
positionList = [position1, position2, position3, //and so on]
but what i get is this (lets say i try to push the array three times)
positionList = [position3, position3, position3]
How do I handle res.download(pathname) on frontend(ReactJS)
I have written a code on my server(NodeJS) that will send a .csv file to the frontend with express res.download(path). I would like to know how I can handle the response with fetch API that will allow the frontend to download the file(.csv) sent.
I am using reactJs on my frontend.
Although I write the necessary codes, I can’t get results
Laptop text and price should appear on the blue button.
Although I write the necessary codes, I can’t get results
<div class="card" style="width: 18rem;" >
<img src="https://picsum.photos/400" class="card-img-top" alt="Card image cap"/>
<div class="card-body" >
<h5 class="card-title">
{{product.name}} {{product.price | currency:'USD':true:"1.2-2"}}</h5>
<p class="card-text">
{{product.description}}
</p>
<a href="#" class="btn btn-primary">Go Somewhere</a>
</div>
and product.price I get an error
It should have written where I marked what the above code requires
Javascript hide/show div when the next button is clicked
I have a page with many images acting as button that when clicked on, reveal a seperate set of images. However, I only want one set to be shown at a time — so that when you click on the next button, it hides the set currently being shown. I’m sure this isn’t too tricky, but I’m such a beginner! Any help would be greatly appreciated. Here is a snippet of my code:
HTML:
<button onclick="contentcarFunction()">
<div class="item" id="carprint">
<img class="thermal-img" src="img/carprint-400px.png" alt="">
</div>
</button>
<div class="content-box" id="carprint-1">
<img class="gallery-img" id="content" src="img/CARPRINT/carprint1.jpeg" alt="">
<img class="gallery-img" id="content" src="img/CARPRINT/carprint2.jpeg" alt="">
</div>
<button onclick="contentyanaFunction()">
<div class="item" id="yana">
<img class="thermal-img" src="img/yana-400px.png" alt="">
</div>
</button>
<div class="content-box" id="yana-1">
<img class="gallery-img" id="content" src="img/DVD/DVDV.jpg" alt="">
<img class="gallery-img" id="content" src="img/DVD/Screen Shot 2020-04-15 at 14.02.47.png" alt="">
</div>
<button onclick="contenttsarFunction()">
<div class="item" id="tsar">
<img class="thermal-img" src="img/tsar1-400px.png" alt="">
</div>
</button>
<div class="content-box" id="tsar-1">
<iframe id="clip" width="560" height="315" src="https://www.youtube.com/embed/wQgjq-Hiz4Y"></iframe>
<img class="gallery-img" id="content" src="img/Tsar/Excursion.gif" alt="">
<img class="gallery-img" id="content" src="img/Tsar/Lecture.gif" alt="">
</div>
JAVA:
function contentcarFunction() {
var x = document.getElementById("carprint-1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function contentyanaFunction() {
var x = document.getElementById("yana-1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function contenttsarFunction() {
var x = document.getElementById("tsar-1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
How can I use datx and mobx in my typescript react project
I’ve been trying to use datx and mobx in my react project for a while now. I always get the following error: The instance needs to be a model, collection or a view. Does anyone have an example of how this works or is there another package that might work well with json:api data?
WebGL Hardware Acceleration – failIfMajorPerformanceCaveat no longer working on Chrome
Previously I was able to detect whether or not the browser has Hardware Acceleration enabled, by using the failIfMajorPerformanceCaveat flag.
const canvas = document.createElement("canvas");
canvas.setAttribute("width", "1");
canvas.setAttribute("height", "1");
const body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
const gl = canvas.getContext("webgl", { failIfMajorPerformanceCaveat: true });
body.removeChild(canvas);
return !gl;
However, this flag no longer seems to fail and the canvas context is still created. I’m on the latest version of Chrome (101.0.4951.67) and using Windows. Can anyone help me?
How to sort an Alphanumeric Array in js? [duplicate]
Original Array
let array=[
"Decathlon 100 Meter Dash",
"Heptathlon 100 Meter Hurdles",
"4x800 Meter Relay",
"Triathlon 200 Meter Dash",
"Heptathlon 800 Meter Run",
"200 Meter Dash",
"800 Meter Run",
"4x100 Meter Relay",
"Combined 3000 Meter Run",
"400 Meter Dash",
"80 Meter Hurdles",
"100 Meter Dash",
"Combined 100 Meter Hurdles",
"100 Meter Hurdles",
"400 Meter Hurdles",
"Combined 4x100 Meter Relay",
"1500 Meter Run",
"Combined 1500 Meter Run",
"4x400 Meter Relay",
]
Expected Array
let
Array=[
"80 Meter Hurdles",
"100 Meter Hurdles",
"100 Meter Dash",
"200 Meter Dash",
"400 Meter Dash",
"400 Meter Hurdles",
"4x100 Meter Relay",
"4x400 Meter Relay",
"4x800 Meter Relay",
"800 Meter Run",
"1500 Meter Run",
"Combined 3000 Meter Run",
"Combined 100 Meter Hurdles",
"Combined 4x100 Meter Relay",
"Combined 1500 Meter Run",
"Decathlon 100 Meter Dash",
"Heptathlon 100 Meter Hurdles",
"Heptathlon 800 Meter Run",
"Triathlon 200 Meter Dash"
]
React useContext to pass person object from signup to phone verification
I working on a portal using react and I am trying to pass the form data which is an object from the signup page to the phone verification page so I can verify and update the phone number in the database.
Below is the phone verification page :
import React, { useContext, useState } from "react";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import "../Styles/phone.css";
import { Link } from "react-router-dom";
import axios from "axios";
import { personContext } from "../Components/Signup-
component";
import { event } from "jquery";
function Phone() {
const [person, setperson] = useContext(personContext);
function clicked() {
console.log(person);
const url = "http://localhost:5000/users";
axios
.put(url, { person })
.then((res) => console.log(res))
.catch((err) => console.log(err.message));
}
return (
<div>
<div className="contained">
<div className="verify mx-auto align-items-center">
<PhoneInput
inputProps={{
name: "phone",
required: true,
autoFocus: true,
}}
country={"ng"}
className="phone"
countryCodeEditable={false}
value={this.state.phone}
onChange={(phone) =>
setperson({
...person,
phone: `${event.target.value}`,
})
}
// onChange={(phone) => this.setState({ phone })}
/>
<br />
<Link to="/Verify" className="text-decoration-none">
<button className="d-block phone-submit mt-3" onClick={clicked}>
SUBMIT
</button>
</Link>
</div>
</div>
</div>
);
}
export default Phone;
below is the Signup component
import React, { createContext, useState } from "react";
import "../Styles/signup.css";
import "bootstrap/dist/css/bootstrap.css";
import { Link } from "react-router-dom";
import axios from "axios";
export const personContext = createContext();
function Signup() {
const [person, setperson] = useState({
FullName: "",
username: "",
email: "",
password: "",
confirmPassword: "",
phone: "",
});
function clicked() {
console.log(person);
const url = "http://localhost:5000/createUser";
axios
.post(url, { person })
.then((res) => console.log(res))
.catch((err) => console.log(err.message));
}
return (
<personContext.Provider value={[person, setperson]}>
<form action="/createUser" method="POST">
<input
type="text"
name="fullname"
placeholder="Fullname"
pattern="[A-Za-z]{9,32}"
className="inp input"
required
autoFocus
onChange={(event) => {
setperson({
...person,
FullName: `${event.target.value}`,
});
}}
/>
....
</form>
</personContext.Provider>
)
export default Signup;
i would appreciate if anyone could help, i am new to react and working to build a nice project.
How to know the height of the div when its overflow is hidden
I have a div, which have overflow hidden. Now want to display a arrow , up and down , up when we have overflow up and down arrow when we have overflow down.
And no arrows if there is no overflow in the div.
Puppeteer won’t let me use Javascript
I’m doing some scraping on a website i’m building. The thing is, i’m using puppeteer to scrape what i need, and i already have all the values i want to display on my website. The problem is that whenever i try to display those values on my HTML, whether using innerHTML or innerText, nothing happens.
After a while i realised that if i try to display a value BEFORE my puppetter code (as shown below), it works, but if i try to do it AFTER requiring puppeteer, nothing happens. I need to display the values scraped using puppeteer, but i can only do it, obviously, after i require it.
Yes, i have used JSON.stringify, and even if i try to declare a variable as a test, it won’t work either (unless i do so before the line of code where i require puppeteer). So the problem is, indeed, the line of code shown below.
TL;DR
If i try to declare a variable HERE (before the line below), and display on my HTML, it works.
const puppeteer = require(‘puppeteer’);
If i try to declare a variable HERE (after de line above), and display on my HTML, it does not work.
firebase is not being recognized in Unity webGL Build
I have set up a test project in order to test Firebase with unity webGL builds.
I have created a *.jslib plugin to keep my js functions in there :
mergeInto(LibraryManager.library, {
GetJSON: function (path, objectName, callback, fallback) {
var parsedPath = Pointer_stringify(path);
var parsedObjectName= Pointer_stringify(objectName);
var parsedCallback = Pointer_stringify(callback);
var parsedFallback = Pointer_stringify(fallback);
try{
firebase.database().ref(parsedPath).once('value').then(function(snapshot) {
window.unityInstance.SendMessage(parsedObjectName, parsedCallback , JSON.stringify(snapshot.val()));
});
} catch(error){
window.unityInstance.SendMessage(parsedObjectName, parsedFallback, "There was an error: " + error.message);
}
}
});
After building and running, I add my Firebase config snippet into the index.html file(I have hidden the actual keys on this snippet):
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-analytics.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "key",
authDomain: "domain",
projectId: "id",
storageBucket: "bucket",
messagingSenderId: "senderID",
appId: "appId",
measurementId: "measurementId"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
In unity, I am testing this by calling the GetJSON function, and I have a callback, and a fallback method:
void Start()
{
text.text = "Start worked";
GetJSON(path: "example", gameObject.name, callback: "OnRequestSuccess", fallback: "OnRequestFailed");
}
public void OnRequestSuccess(string data)
{
text.color = Color.green;
text.text = data;
}
public void OnRequestFailed(string error)
{
text.color = Color.red;
text.text = error;
}
After I have built and run my webGL project, and updated the index.html file with the proper configurations, the text turns red (Which means the OnRequestFailed() was called) and it says: “There was an error: firebase is not defined”. Which means, it does not recognize the firebase when I use it on the *.jslib plugin. Where should the firebase be defined exactly? Because I am defining it in my index.html, or at least I think so?



