Google introduced new Sign In JS library(gsi
) a long time ago but Google Sheets documentation still shows examples using gapi
. What would be the best approach to combine/replace gapi with gsi? May I have an example?
Category: javascript
Category Added in a WPeMatico Campaign
Adding one line of code in my project changes the whole program dramatically, please assist me?
So I only have a week’s worth of HTML, CSS, and JavaScript experience, and I’ve been trying to create a game similar to the Dinosaur game on Chrome. I’ve come across a problem trying to store a High Score. For some reason, when I try to update the normal score, the whole game disappears.
Here’s my insulting code:
HTML
<!DOCTYPE html>
<html lang="en" onclick="jump()">
<head>
<style>
#title
{
left: 2px;
position: relative;
}
#highscore
{
left: 450px;
top: 23px;
position: fixed;
}
</style>
<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>Block Game</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h3 id="title">Block Game</h3>
<div id="game">
<div id="score">Score: <br>0</br><div>
<div id="highscore">Highscore: <br>0</br></div>
<div id="character"></div>
<div id="longBlock"></div>
<div id="block"></div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS
* {
padding: 0;
margin: 0;
}
#game {
width: 520px;
height: 200px;
left: 2px;
position: relative;
border: 1px solid black;
}
#character {
width: 20px;
height: 50px;
left: 20px;
background-color: grey;
position: relative;
top: 114px;
}
.animate {
animation: jump 500ms;
}
#block {
width: 20px;
height: 20px;
background-color: red;
position: relative;
top: 74px;
left: 500px;
animation: block 1.5s infinite linear;
}
#longBlock {
width: 40px;
height: 20px;
background-color: blue;
position: relative;
top: 94px;
left: 500px;
animation: block 2s infinite linear;
}
@keyframes block {
0% {
left: 480px;
}
100% {
left: -40px;
}
}
@keyframes jump {
0% {
top: 114px;
}
20% {
top: 67px;
}
30% {
top: 62px;
}
70% {
top: 62px;
}
90% {
top: 109px;
}
100% {
top: 114px;
}
}
JavaScript
var score = 0;
var highscore = 0;
var character = document.getElementById("character");
var block = document.getElementById("block");
var longBlock = document.getElementById("longBlock");
document.getElementById("highscore").innerHTML = "High Score: n" + highscore;
document.getElementById("score").innerHTML = "Score: n" + score;
localStorage.clear();
window.onload = function()
{
var scoreFromBrowser = localStorage.getItem("highscore");
if(scoreFromBrowser!= undefined)
{
highscore = scoreFromBrowser;
document.getElementById("highscore").innerHTML = "High Score: " + highscore;
}
}
var addScore = setInterval(function(){
score+=1;
document.getElementById("score").innerHTML = "Score: n" + score;
if(score>highscore)
{
localStorage.setItem("highscore", highscore);
highscore = score;
document.getElementById("highscore").innerHTML = "High Score: n" + highscore;
}
},200);
function jump(){
if(character.classList!="animate"){
character.classList.add("animate");
}
setTimeout(function(){
character.classList.remove("animate");
},500);
}
var checkDead = setInterval(function(){
var characterTop =
parseInt(window.getComputedStyle(character).getPropertyValue("top"));
var blockLeft =
parseInt(window.getComputedStyle(block).getPropertyValue("left"));
var longBlockLeft =
parseInt(window.getComputedStyle(longBlock).getPropertyValue("left"));
if(blockLeft<44 && blockLeft>=5 && characterTop<=130 && characterTop>=84)
{
block.style.animation = "none";
alert("You Lose. Highscore: " + highscore);
if(!alert('Replay?'))
{
window.location.reload();
}
}
else if(longBlockLeft<43 && longBlockLeft>=5 && characterTop<=130 && characterTop>=74)
{
block.style.animation = "none";
alert("You Lose. Highscore: " + highscore);
if(!alert('Replay?'))
{
window.location.reload();
}
}
},15);
I wrote this on VSCode and ran it with Live Server. If you delete all the parts like this, document.getElementById("score").innerHTML = "Score: n" + score;
The game appears normally. Please Help.
Why won’t file uploads work on the browser despite it working in Postman?
I’m not sure why when making a POST request on Postman, I’m successfully storing the URLs in the DB by grabbing the file and retrieving its name.
But when I try it on the browser, I get a 500 error. The auth token’s coming back correctly, the logged data is also containing the correct information so it’s not entirely clear to me what I’m doing wrong even though I’m doing it exactly the same way as how I’m doing it in Postman and it works fine there.
In the server logs I see an error that says: Call to a member function getClientOriginalName() on null
but as mentioned before – the upload works fine on Postman.
What could be issue?
Here’s my JS:
const [selectedFile, setSelectedFile] = useState(null);
let authToken = localStorage.getItem('token');
const onFormSubmit = (e) => {
e.preventDefault()
fileUpload(selectedFile);
}
const onChange = (e) => {
let files = e.target.files || e.dataTransfer.files;
if (!files.length) {
return;
}
createImage(files[0]);
}
const createImage = (file) => {
let reader = new FileReader();
reader.onload = (e) => {
setSelectedFile(e.target.result);
};
reader.readAsDataURL(file);
}
const fileUpload = (selectedFile) => {
const url = 'http://localhost:8005/api/file-upload';
const formData = {file: selectedFile}
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
}
console.log(authToken);
console.log(formData);
console.log(headers);
JSON.stringify(formData);
axios.post(url, formData, {
headers: headers
}).then(resp => {
console.log(resp);
}).catch(error => {
console.log(error);
});
}
return (
<form>
<input type="file" onChange={onChange} name="userUpload" required/>
<Button variant="primary" onClick={onFormSubmit}>Upload!</Button>
</form>
);
“Cannot read properties of undefined” Error when using absolute import in react
I am building a game, and have set up absolute importing in my react app with jsconfig.json like this:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
and I do have a Config folder with a bunch of config files, and an index.js file that exports them all in a single module, like this:
export { default as PhaserConfig } from "./Phaser.Config"
export * as Objects from "./Objects.Config"
export * as Prefabs from "./Prefabs.Config"
export * as InventoryItems from "./Items.Config"
export {
initKeyboardInput,
StarterInventoryItems,
ColorPallete,
} from "./Game.Config"
so now whenever importing something like this:
import { Objects } from "Config"
console.log(Objects.Sprite) // throws "Cannot read properties of undefined" error
The weird thing is, when launching my react app, there are no errors in the console, it’s just an error message that appears in the react app itself in the browser. Please help!
Mobile site whitening
Hi I have a WordPress site
When I open this site with my mobile, the site page turns completely white for one second. But this problem does not exist in the computer.
I disabled and tested all plugins but it did not work.
What should I do now? If anyone knows please help
add subcategory to category tree in Reactjs
I have a category tree and I want to add a subcategory to it by the “+” button shown inside the subcategory in the picture below.
my problem is I want to add this subcategory to the specific “cloths” category for example, not to all categories, I have an idea of using the category ID I can’t figure out how to do it!
I’ve written this code so far! and I am using JSON-server for fake API calls as follows:
import { Formik, Field, Form } from 'formik';
import React, { useEffect } from 'react';
import { getData, postDataDefaultHeader } from '../../Services/Api';
import Modal from '../Modal/Modal';
const ManageCategories = () => {
const [categories, setCategories] = React.useState(false);
const [isSubmit, setIsSubmit] = React.useState(false);
const [addButton, setAddButton] = React.useState(false);
useEffect(() => {
getData(`${process.env.REACT_APP_API}/categories`, setCategories);
if (isSubmit) {
getData(`${process.env.REACT_APP_API}/categories`, setCategories);
setIsSubmit(false);
}
}, [isSubmit]); //only get categories data when categories is truthy
return (
<div>
<Formik
initialValues={{
categoryName: '',
}}
onSubmit={(values) =>
postDataDefaultHeader(
`${process.env.REACT_APP_API}/categories`,
values
)
}
>
{({ values }) => (
<Form>
<Field
name="categoryName"
type="text"
placeholder={'add new category'}
/>
<button onClick={() => setIsSubmit(true)} type="submit">
save
</button>
</Form>
)}
</Formik>
<div>
{categories &&
categories.map((category) => (
<dl key={category.categoryName}>
<dt>{category.categoryName}</dt>
{category.subCategory &&
category.subCategory.map((subCate) => (
<dd
key={subCate.subCategoryName}
value={subCate.subCategoryName}
>
{subCate.subCategoryName}
<div>
<button
onClick={(id) => {
if (id === category.id) {
setAddButton(!addButton);
}
}}
>
+
</button>
{addButton && (
<div>
<input type="text" /> <button>حفظ</button>
</div>
)}
</div>
</dd>
))}
</dl>
))}
</div>
</div>
);
};
export default ManageCategories;
Typescript way to optimise nested for loop
I have the following nested for loop in my code. this works fine but i am not sure whether this is a good way to do it.i would like to know what is the best optimised way to handle such cases in typescript to get rid of for loops.
for (let j = 0; j <= list.length - 1; j++) {
const student = list[j];
for (let i = 0; i <= selectedStudent.subs.length - 1; i++) {
const id = selectedStudent.subs[i].id;
if(student[id] === id){
console.log(id);
}
}
}
How do I combine JavaScript and HTML into a script tag for embedding? [closed]
I’ve been tasked at my internship with adding a range slider with styling into The Gohighlevel platform. I’m very confused on how to write it altogether so they can add it to a section of the site. There is a place in gohighlevel to add custom html/JS but I’m just not sure how to write it. As a disclaimer they’ve had me recreate this slider from react so it can go into the site. I’ve done all of that. I just need an example of how I should write it so they can just embed it on the site and it works. Any help would be appreciated. I find very little documentation about custom code on gohighlevel so it’s getting frustrating. I’ve never done anything like this.
I cannot get toggle state to remember state on refresh, using alpinejs and tailwindcss
I have a toggle using TailwindCSS that when toggled sets a localStorage to true or false. This works, albeit it sets false when on. But my problem is that when the page refreshes the localStorage sticks but the toggle doesn’t and defaults the button to on.
Can anyone explain to me how I can achieve this? It would be greatly appreciated.
Here’s the codepen.
https://codepen.io/williamharvey/pen/xxXaJgM
And here’s the code.
<div
class="flex w-full items-center bg-gray-100 border-b border-gray-200 px-5 py-3 text-sm"
x-data="{cookieConsent3: localStorage.getItem('Consent3') === 'true'}"
x-init="$watch('cookieConsent3', val => localStorage.setItem('Consent3', val))"
x-bind:class="{ 'Consent3': cookieConsent3 }">
<div class="flex-1">
<p>Cookies that measure website use</p>
</div>
<div class="w-10 text-right">
<button type="button"
class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-300 bg-gray-200"
x-data="{ on: true }"
role="switch"
aria-checked="false"
:aria-checked="on.toString()"
@click="on = !on;cookieConsent3 = !cookieConsent3"
x-state:on="Enabled"
x-state:off="Not Enabled"
:class="{ 'bg-green-400': on, 'bg-gray-200': !(on) }">
<span class="sr-only">Use setting</span>
<span aria-hidden="true" class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200 translate-x-0" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'translate-x-5': on, 'translate-x-0': !(on) }"></span>
</button>
</div>
</div>
How to prevent checkbox from being checked when a node is clicked on JSTree?
I don’t want the checkbox to be checked when the node is clicked, only when the checkbox itself is clicked.
The code below was copied from the JSTree website I think, and I copied a few lines from a tutorial to enable checkboxes.
$('#ajaxx').jstree({
'core' : {
'data' : {
"url" : (node)=>{
return node.id === '#' ?
'./dirfilesapi.php?dirID=-1' :
('./dirfilesapi.php?dirID='+node.id);
},
"dataType" : "json" // needed only if you do not supply JSON headers
}
},"checkbox" : {
"keep_selected_style" : false
},
"plugins": ["checkbox"]
});
This code runs for grid=12. Can anyone explain why this happens?
Basically the title. I have read every line many times and still can’t find my mistake.
I am just trying to put squares on a grid by calling a recursive function which creates the object and then calls itself again. I have checked that recursion is not infinite and there’s a simple exit condition. Please help.
let grid = 11;
let sqr = [];
function setup() {
createCanvas(grid * grid, grid * grid);
noFill();
colorMode(HSB);
noLoop();
let maxs = floor(grid / 3);
let ratio = 2 * maxs * maxs;
makegrid(maxs, ratio);
}
function draw() {
background(0);
for (let sq of sqr) sq.show();
}
function makegrid(m, r) {
if (!m) return;
if (m == floor(grid / 3)) {
for (let i = 0; i < 2; i++) sqr.push(new sqrs(m, r));
m--;
makegrid(m, r);
} else {
let j = r / (m * m);
for (let k = 0; k < j; k++) sqr.push(new sqrs(m, r));
m--;
makegrid(m, r);
}
}
class sqrs {
constructor(m, r) {
let flag = true;
this.s = (m * width) / grid;
while (flag) {
flag = false;
this.x = (width / grid) * floor((grid + 1 - m) * random());
this.y = (height / grid) * floor((grid + 1 - m) * random());
if (!sqr.length) flag = false;
else {
for (let sq of sqr) {
let d = (this.x - sq.x) ** 2 + (this.y - sq.y) ** 2;
if (d < this.s ** 2 || d < sq.s ** 2) {
flag = true;
break;
}
}
}
}
}
show() {
stroke(random(340), 80, 80);
square(this.x, this.y, this.s);
}
}
How to seed/upload images in KeystoneJS 6?
Using the example here, if I then add an image field to Post:
// schema.ts
import { list } from '@keystone-6/core';
import { select, relationship, text, timestamp } from '@keystone-6/core/fields';
export const lists = {
Post: list({
fields: {
featureImage: image(),
}),
/* ... */
},
/* ... */
});
How can I then adjust the seed/index.ts
file to upload an image form the local drive?
// seed/index.ts
await context.query.Post.createOne({
data: {
...postData,
featureImage: { /* ??? What goes here ??? */ }
},
query: 'id',
});
Or otherwise, how can I programmatically add images so that keystonejs is aware of them?
I have this logic to loop over my value passed as argument and print them one letter per second
let sequenceI = 0;
function sequence(arr){
document.getElementsByTagName('P')[0].innerHTML += arr[sequenceI];
++sequenceI;
setTimeout(() => sequence(arr), 150);
if (sequenceI > arr.length) {
document.getElementsByTagName('P')[0].innerHTML ="";
sequenceI = 0;
}
}
sequence('Software Developer');
I have this logic to loop over my value passed as argument and print them one letter per second. Why does this not return undefined when the sequenceI becomes 18? But it rather starts the loop again
closePath() Moving Polygon
The following code below is what is needed to make a simple triangle. I want to keep the triangle in that exact position and add this to my canvas.
can = document.getElementById("gameCanvas");
var ctx = can.getContext("2d");
ctx.beginPath();
ctx.moveTo(1, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.closePath();
ctx.stroke();
If you run the code below, the triangle is there for a split second and then disappears. I need it to stay there along with the three equations. I created the function path(); in effort to keep the triangle positioned in the upper left corner. I am not sure how to keep the triangle there and do all of this.
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#gameCanvas {
background-color: lightyellow;
}
</style>
<div class="canvasHolder1">
<div id="eqn1"> 3+3=<input type="text" id="q1" />
</div>
<div id="eqn2"> 3+2=<input type="text" id="q2" />
</div>
<div id="eqn3"> 5+2=<input type="text" id="q3" />
</div>
<canvas id="gameCanvas" width="600" height="600">Not supported</canvas>
<script type="text/javascript">
var m=1;
var stage = new createjs.Stage("gameCanvas");
var obj=[];
can = document.getElementById("gameCanvas");
var ctx = can.getContext("2d");
ctx.beginPath();
ctx.moveTo(1, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.closePath();
ctx.stroke();
function startGame() {
obj[1] = new createjs.DOMElement(document.getElementById(`eqn${1}`));
obj[2] = new createjs.DOMElement(document.getElementById(`eqn${2}`));
stage.addChild(obj[1]);
stage.addChild(obj[2]);
createjs.Ticker.addEventListener("tick", handleTick);
createjs.Ticker.setFPS(60);
function handleTick(event){
drop(1);
drop(2);
path();
stage.update();
}
}
function drop(i){
obj[1].x =40;
obj[1].y =50;
obj[2].x =300;
obj[2].y =50;
}
function path(){
ctx.x=1;
ctx.y=1;
}
</script>
<body onload="startGame();">
<div >
<canvas>This browser or document mode doesn't support canvas object.</canvas>
</div>
</body>
</html>
JavaScript: group array of objects by property in an object
if I have a js array like below, is there a simple way to re-group the array values by age? I tried to reduce it to an array but it did not help. it’s re-grouped with age or name’s
let employees = [
{
firstName:"Zion",
lastName: "Rosy",
age: 25,
joinedDate:"January 24, 2020",
},
{
firstName: "Ana",
lastName: "Rosy",
age: 25,
joinedDate: "January 15, 2019",
},
{
firstName: "Zion",
lastName:"Albert",
age: 30,
joinedDate:"February 15, 2011",
},
];
To re-group by age like this:
let organizedByAge =
{
25: [
{
firstName:"Zion",
lastName: "Rosy",
age: 25,
joinedDate:"January 24, 2020",
},
{
firstName: "Ana",
lastName: "Rosy",
age: 25,
joinedDate: "January 15, 2019",
},
],
30: [
{
firstName:"Zion",
lastName:"Albert",
age: 30,
joinedDate:"February 15, 2011",
},
],
};