follow focus on form textfield when it clicked to fill in web mobile ver

i’m a new learner in web development. so , sorry if this question make u fill confused for what i mean.

i found a problem when i saw my web page in mobile version on form textarea.
everytime i clicked the field area to fill it and click the button beside.
the keyboard always closes the textfield area, and makes viewport behind it zoomed out.

i set the position form to relative by the way.

this i attach the view before and after i click it.

pic before
pic after

and this the code for the html and css i use,
(let me know if this need to be solve by jquery and javascript ) :

        <div class="newslatter">
            <form>
                <input type="email" name="email" id="mail" placeholder="Enter Your Email" autofocus required>
                <input type="submit" name="submit" value="Let's Start !">
            </form>
        </div>

for the css :

.newslatter form {
  width: 380px;
  max-width: 100%;
  position: relative;
}
.newslatter form input:first-child {
  display: inline-block;
  width: 100%;
  padding: 14px 130px 14px 15px;
  border: 3px solid var(--main-color);
  outline: none;
  border-radius: 30px;
}
.newslatter form input:last-child {
  position: absolute;
  display: inline-block;
  outline: none;
  border: none;
  background-color: var(--main-color);
  color: white;
  border-radius: 30px;
  padding: 10px 30px;
  box-shadow: 0 0 5px #000, 0 0 15px #858585;
  top: 7px;
  right: 6px;
  cursor: pointer;
  transform: 0.5s;
}
.newslatter form input:last-child:hover {
  transform: scale(0.95);
}

Store prop as useState

I want to achieve sorting function from child, where the props are pass in from parent from an axios call- Should I

  1. store prop in child useState
  2. pass in parent setState from prop
    for achieve that?

Assume that I do not need parent rerender for sorting, my thinking is 1 could be more favourable – it just that I am not sure storing prop in setState is a common pattern.

First case (codesandbox) – store prop in child useState

parent jsx

import { useEffect, useRef, useState } from "react";
import "./styles.css";
import Child from "./Child";

export default function Parent() {
  const taskRefs = useRef([]);
  const [cellContent, setCellContent] = useState([2, 1, 3]);

  useEffect(() => {
    console.log("parent render")
  });

  useEffect(() => {
    //this content is get from axios call
    setCellContent([3, 2, 1]);
  }, []);

  return <Child cellContent={cellContent} />;
}

child jsx

import { useEffect, useState } from "react";
import "./styles.css";

export const Child = ({ cellContent }) => {
  const [sortState, setSortState] = useState(cellContent);
  useEffect(() => {
    console.log(cellContent);
  }, []);

  const sort = (a) => {
    cellContent?.sort();
    setSortState(cellContent);
  };
  return (
    <div className="App">
      <button onClick={sort}>sort</button>
      <div>{sortState?.map((a) => a)}</div>
    </div>
  );
};

export default Child;

Second case (codesandbox) -pass in parent setState from prop

parent jsx

import { useEffect, useRef, useState } from "react";
import "./styles.css";
import Child from "./Child";

export default function Parent() {
  const [cellContent, setCellContent] = useState([2, 1, 3]);

  useEffect(() => {
    console.log("parent render");
  });

  useEffect(() => {
    //this content is get from axios call
    setCellContent([3, 2, 1]);
  }, []);

  return (
    <Child cellContent={[...cellContent]} setCellContent={setCellContent} />
  );
}

Child jsx

import { useEffect, useState } from "react";
import "./styles.css";

export const Child = ({ cellContent, setCellContent }) => {
  useEffect(() => {
    console.log(setCellContent);
  }, []);

  const sort = (a) => {
    cellContent?.sort();  
    setCellContent(cellContent);
  };
  return (
    <div className="App">
      <button onClick={sort}>sort</button>
      <div>{cellContent?.map((a) => a)}</div>
    </div>
  );
};

export default Child;

On page refresh Projects Context is returning projectsMap as undefined. How do I fix this?

When I refresh the Projects page, my Projects Context is returning projectsMap as undefined causing the error: Uncaught TypeError: can’t convert undefined to object. However, when I comment out

**{
          Object.keys(projectsMap).map((id) => {
      const projects = projectsMap[id];
      return (
        <h1 key={id}>{projects.name}</h1>
      );
    })
      }**

and uncomment the code I don’t have any errors. I assume this has to do with the async await assignment of projectMap to the return value from getProjects(currentUser). Any help would be greatly appreciated. Below is the code from firebase.utils for getProjects, the projects.context file and the projects.component.jsx files respctivly.


    firebase.utils.js:
    
    export const getProjects = async (userAuth) => {
      if (!userAuth) return;
      const projectsCollectionRef = collection(
        db,
        "users",
        userAuth.uid,
        "projects"
      );
      const q = query(projectsCollectionRef);
      try {
        const querySnapshot = await getDocs(q);
        const projectMap = querySnapshot.docs.reduce((acc, docSnapshot) => {
          const id = docSnapshot.id;
          const { name } = docSnapshot.data();
          acc[id] = {id, name};
          return acc;
        }, {});
        return projectMap;
      } catch (error) {
        console.log("Error getting project docs.");
      }
    };
    
    projects.context.jsx:
    
    import { createContext, useContext, useState, useEffect } from "react";
    import { UserContext } from "./user.context";
    
    import { getProjects } from "../utils/firebase/firebase.utils";
    
    export const ProjectsContext = createContext({
      projectsMap: {},
    });
    
    export const ProjectProvider = ({ children }) => {
      const [projectsMap, setProjectsMap] = useState({});
      const { currentUser } = useContext(UserContext);
    
      useEffect(() => {
        const getProjectsMap = async () => {
          const projectMap = await getProjects(currentUser);
          setProjectsMap(projectMap);
        };
        getProjectsMap();
      });
    
      const value = { projectsMap };
    
      return (
        <ProjectsContext.Provider value={value}>
          {children}
        </ProjectsContext.Provider>
      );
    };
    
    Projects.context.jsx:
    
        import { useEffect, useContext } from "react";
        import { Outlet } from "react-router-dom";
        
        import { UserContext } from "../../contexts/user.context";
        import { ProjectsContext } from "../../contexts/projects.context";
        
        import { getProjects } from "../../utils/firebase/firebase.utils";
        import CreateProjectForm from "../../components/create-project/Create-Project-Form.component";
        
        const Projects = () => {
          const { projectsMap } = useContext(ProjectsContext);
        
         
        
          return (
            <>
              <CreateProjectForm />
              {
                  Object.keys(projectsMap).map((id) => {
              const projects = projectsMap[id];
              return (
                <h1 key={id}>{projects.name}</h1>
              );
            })
              }
              <Outlet />
            </>
          );
        };
        
        export default Projects;

How to store data | MERN Stack

I am a beginner at MERN Stack. I can create and save users from Postman
API, but I want users to register independently, and navigate the Login page. What will I do?

I am trying to create Register.jsx to save, but data cannot be saved 🙁

(I remove the style element because I cannot post my question)

Register.jsx (from Client side)

import { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { mobile } from "../responsive";

const Container = styled.div``;

const Wrapper = styled.div``;

const Title = styled.h1``;

const Form = styled.form``;

const Input = styled.input``;

const Agreement = styled.span` `;

const Button = styled.button``;

const Register = () => {
  const[user, setUser] = useState({
    username: "",
    email: "",
    password: "",
  });

  const navigate  = useNavigate();

  const handleChange = e => {
    const {name,value} = e.target;
    
    setUser({...user, [name]:value});
  };

  const handleClick = async (e) => {
    e.preventDefault();
    const { name, email, password } = user;
    const res = await fetch("/register", {
      method: "POST",
      headers: { "Content-Type" : "application/json"},
      body: JSON.stringify({
        name, email, password
      })
    });
    const data = await res.json();

    if(res.status === 500 || !data){
      window.alert("Invalid Registration");
      console.log("Invalid Registration");
    } else {
      window.alert("Registration Successfull");
      console.log("Registration Successfull");
      navigate("/login");
    }
  };
  return (
    <Container>
      <Wrapper>
        <Title>CREATE AN ACCOUNT</Title>
        <Form method="POST">
          <Input 
            placeholder="username" 
            type="text"
            name="username"
            value={user.username}
            required
            onChange={handleChange}
          />
          <Input placeholder="email" 
            type="email"
            name="email"
            value={user.email}
            required
            onChange={handleChange}
          />
          <Input placeholder="password" 
            type="password"
            name="password"
            value={user.password}
            required
            onChange={handleChange}
          />
          <Button onClick={handleClick}>CREATE</Button>
        </Form>
      </Wrapper>
    </Container>
  );
};
export default Register;

auth.js (server-side)

const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
const jwt = require("jsonwebtoken");

//REGISTER
router.post("/register", async (req, res) => {
  const newUser = new User({
    username: req.body.username,
    email: req.body.email,
    password: CryptoJS.AES.encrypt(
      req.body.password,
      process.env.PASS_SEC
    ).toString(),
  });
  try {
    const savedUser = await newUser.save();
    res.status(201).json(savedUser);
  } catch (err) {
    res.status(500).json(err);
  }
});

How to build logic checking for wins,lose,and tie within JavaScript Tic-Tac-Toe

I am creating a tic-tac-toe game in html,CSS,and JavaScript. I want to check when the game is over in the form of tie, win or loss. However for some reason my functions aren’t working and aren’t returning either a tie win or loss upon selection of a winning Combination. Codepen (https://codepen.io/nolimitz71/pen/jOYENdL) . Here is the JS:


    const gameBoard = (() => {
        var initialPLayer = "X";
        var board = [];
        var gameResults = document.querySelector('#warning');
        var playerDisplay = document.querySelector("#para-display")
        var cells = document.querySelectorAll("#box");
        var boardBoxes = document.getElementById("piece").getElementsByTagName("td");
    
        const winningCombos = [
            [0, 1, 2],
            [3, 4, 5],
            [6, 7, 8],
            [0, 3, 6],
            [1, 4, 7],
            [2, 5, 8],
            [0, 4, 8],
            [2, 4, 6]
        ]
    
    
        function playerMovement() {
            if (initialPLayer === 'X') {
                initialPLayer = "O";
                playerDisplay.innerHTML = "O"
            } else {
                initialPLayer = "X";
                playerDisplay.innerHTML = "X"
            }
        }
    
        function playGame() {
            if (this.innerHTML == '') {
                this.innerHTML = initialPLayer;
                playerMovement();
            }
        }
    
        var boardBoxes = document.getElementById("piece").getElementsByTagName("td");
        for (var i = 0; i < boardBoxes.length; i++) {
            boardBoxes[i].onclick = playGame;
        }
        document.getElementById("reset").onclick = function() {
            for (var i in boardBoxes) {
                boardBoxes[i].innerHTML = '';
            }
        }
    
        function gameLogic() {
            if (checkWinX()) {
                gameResults.innerHTML = "Player X wins the game"
            }
            if (checkWinO()) {
                gameResults.innerHTML = "Player O wins the game"
            }
            if (Tie()) {
                gameResults.innerHTML = "Tie!!"
            }
        }
        gameLogic()
    
        function checkWinX() {
            return winningCombos.some((combination) => {
                return combination.every((i) => {
                    return cells[i].innerHTML === "X";
                })
            })
        }
    
        function checkWinO() {
            return winningCombos.some((combination) => {
                return combination.every((i) => {
                    return cells[i].innerHTML === "O";
                })
            })
        }
    
        function Tie() {
            return cells.forEach((cells) => {
                return cells.innerText === "X" || cells.innerText === "O";
            })
        }
    
    
    })();```
    
    **HTML:** 
    ```<!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>Tic-Tac-Toe</title>
        <link rel = "stylesheet" href="styles.css">
    </head>
    <body>
        <h1>Tic-Tac-Toe</h1>
        <div id = "game">
          <table id = "piece">
             <div class = "control">
              <tr  id = "board1">
                  <td  id = "box" class = 'cell'></td>
                  <td  id = "box" class = 'vert cell1'></td>
                  <td id = "box" class = "cell2"></td>
              </tr>
              <tr id = "board2">
                  <td  id = "box" class = 'hori cell3'></td>
                  <td id = "box" class = "vert hori cell4"></td>
                  <td id = "box" class = "hori cell5"></td>
              </tr>
              <tr id = "board3">
                  <td  id = "box" class = "cell6"></td>
                  <td id = "box"  class = "vert cell7"></td>
                  <td  id = "box"  class = "cell8"></td>
              </tr>
            </tbody>
        </div>
          </table>
          <button id = "reset">New Game</button>
          <p id = "result">It's <span id="para-display">X</span>'s turn.</p>
          
          <p id="warning"></p>
    <script src = "app.js" defer></script> 
    </body>
    </html>```

Firebase get doc ID that is nested several branches up

I am trying to search for all documents that contain a field, this field is contained in many documents. It’s a UID for users. I am trying to find all documents which contain a certain UID. Given the following struct:

projects > aa (or bb or cc etc many here) > projectTickets > someDocID (which contains the field).

So, I am trying to get the name of the first doc (aa for example). I am not sure how.So, I want to find all documents whose field value match the UID, and go up like 2 branches, and collect that name. Is this possible?

How to pass data to JavaScript ajax xmlhttprequest

function fetchJSONFile(isRest, path, callback) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {
        var data = JSON.parse(httpRequest.responseText);
        if (callback) callback(data);
      }
    }
  };

  httpRequest.open('POST', path, true);
  if (isRest) {
    let mail = "***";
    let pw = "***";
    httpRequest.setRequestHeader("Authorization", "Basic " + window.btoa(mail + ":" + pw));
  }
  httpRequest.send("--data '[1, 2]'"); // also tried data=[1, 2]
}

I want to pass my data to the request, so that i’m able to get a response with the data i need. Currently i’m getting 415 error. What’s wrong with my code?

Porting simple thinkscript volume indi to javascript

This should be an easy one but I’m unfamiliar with javascript. I’ve been trying to put something together but can’t get it to work. The indicator sums the volume of the up candles (green bars) and subtracts it from the sum of down candles (red) over a defined number of bars. It has 2 more plots that are averages of that difference in volume. I’ve attached the output of the thinkscript code. Any help is appreciated. I can venmo $ to the user that replicates the code in javascript. I will be using the ported code in Tradovate. Thanks.

declare lower;
input period = 20;
plot ZEROLINE = 0;
ZEROLINE.SetDefaultColor(Color.GRAY);
ZEROLINE.SetLineWeight(2);


#Green VS Red candle volume difference
def GreenCandle = close > open;
def RedCandle = close < open;
def smacountup = if GreenCandle  then volume else 0;
def smacountdown = if RedCandle  then volume else 0;
def smauptotal = Sum(smacountup, period);
def smadowntotal = Sum(smacountdown, period);
def countup = (smauptotal - smadowntotal);


#green/red candle difference based on countup
def high = if countup >= 0 then volume else 0;
def low = if countup < 0 then volume else 0;
def highfinal = Sum(high, period);
def lowfinal = Sum(low, period);
plot updown = highfinal - lowfinal;
plot updownavg = expaverage(updown, 5);
plot updownavg2 = expaverage(updown, 30);

This what I came up with after a few days and I know it’s not even close and probably way off.

const predef = require("../tools/predef");
const meta = require("../tools/meta");

const defaultBearColor      = "#F23051";
const defaultBullColor      = "#3EB242";
const defaultVolAvgColor    = "yellow";
const defaultVolAvgPeriod   = 8;
const defaultVolAvgPeriod2   = 5;
const defaultVolAvgPeriod3   = 30;
//const defaultLineWidthPx    = 3;

class jtDelta {
    init() {
        this.smaAlgo = SMA(this.props.volAvgPeriod);
    }
    
    map(d) {
        var volume = d.volume();
        var close = d.close();
        var opne = d.open();
        var upCandle = close > open;
        var downCandle = close < open;
        var upCount = 
              if (upCandle) {
                result = volume;
              } else {
                result = 0;
                }
                return result;
                };
        var downCount =
                if (downCandle) {
                    result = volume;
                } else {
                    result = 0;
                    }
                    return result;
        var upTotal = sum(upCount.volAvgPeriod);
        var downTotal = sum(downCount.volAvgPeriod);
        const upDownTotal = (upTotal-downTotal);
        const expavg1 = ema(upDownTotal.volAvgPeriod2);
        const expavg2 = ema(upDownTotal.volAvgPeriod3);
}
        return {
            upDownTotal: upDownTotal,
            expavg1: expavg1,
            expavg2: expavg2,
        };
    }
}



module.exports = {
    name: "jtDelta",
    description: "jtDelta",
    calculator: jtdelta,
    plots: {
        upDownTotal: { title: "1" },
        expavg1: { title: "2" },
        expavg2: { title: "3" },
    },
    tags: ["Volume-based"],
    inputType: meta.InputType.BARS,
    }
};

How do I split a string only when capitalized letters are sticking together

how do I split a string ONLY if two capitalized letters are next to one another without spaces. so, only if ‘AB’ but not if ‘A B’

I want to split:

'John DoeJane DoeOther Doe'

into

['John Doe', 'Jane Doe', 'Other Doe']

I already know how to split just by capitalized letters, like on this issue right here. But I don’t want to split for every capitalized letter and separate ‘John’ from ‘Doe’ or any of the others.

Spaces don’t work when I add a decoration to snippets in codemirror

I’m trying to add background color on anything that is within {{ }} or [[ ]] in codemirror

I got the background on the text but I’m unable to insert spaces after the last }. If it is anything other than space then it shows up and the space is behind that letter.

removing plugin, spaces work fine –
https://gfycat.com/sizzlingmiserableantbear

adding plugin spaces don’t work then –
https://gfycat.com/nervousdearcommabutterfly

here is the codemirror plugin/extension that handles the decoration

const expression = Decoration.mark({
  attributes: { class: 'cm-mdb-expression' },
});

function expressionDeco(view: EditorView) {
  const builder = new RangeSetBuilder<Decoration>();

  for (const { from, to } of view.visibleRanges) {
    for (let pos = from; pos <= to; ) {
      const line = view.state.doc.lineAt(pos);
      const from = line.text.indexOf('{{');
      const to = line.text.indexOf('}}');
      if (from > -1 && to > -1 && to + 2 <= line.length) {
        builder.add(from, to + 2, expression);
      }
      pos = line.to + 1;
    }
  }
  return builder.finish();
}

const showExpressionPlugin = ViewPlugin.fromClass(
  class {
    decorations: DecorationSet;

    constructor(view: EditorView) {
      this.decorations = expressionDeco(view);
    }

    update(update: ViewUpdate) {
      if (update.docChanged || update.viewportChanged) this.decorations = expressionDeco(update.view);
    }
  },
  {
    decorations: (v) => v.decorations,
  }
);

export function expressionBackground(): Extension {
  return [showExpressionPlugin];
}

Getting 401 Unauthorized error while requasting GitHub API

Good evening. My task is to create a website with react that will list through github users. I was following this instruction: https://docs.github.com/en/rest/users/users#get-a-user (for JS). My credentials:

async function searchUsers() {
  try {
    const octokit = new Octokit({
      auth: 'ghp_MY_PERSONAL_TOKEN',
      acceptstring: 'application/vnd.github.v3+json'
    })
    const response = await octokit.request(`GET /users/${name}`, {
      username: 'maria98kgm'
    });

    setUsers(response.data);
    setLoading(false);
    searchRepos();
    } 
    catch(e) {
      setLoading(false);
      setUsers('notFound');
      console.error('no such a user');
   }
}

Whenever i use it too long or push changes to github, it stops working and gives me 401 Unauthorized error:
enter image description here

I cannot solve it for two days already, please help.

vuejs 3 composition API

Anyone know why the variable number doesn’t display the latest value when click on it? I tried using onMounted, but didn’t seem to do anything. When I clicked on the paragraph it always displays 1. I expect it to display the latest number added. Any ideas?


<script setup>

  import TheWelcome from '@/components/TheWelcome.vue'
  import { onMounted, ref  } from 'vue'
  import axios from "axios"

  let number = 1; 
    
  function getCurrentNumber() {
    
    number++;

    console.log(number)
  }

</script>


<template>

  <main>
    <TheWelcome />
  </main>
  <p @click="getCurrentNumber">Hello, this is a test to display {{number}}</p>

</template>


Converting time to another timezone JS

I’m obtaining data.value which is a time in the format: hh:mm a – for example 12:30 am.

I also know:

  1. the local timezone of the user (userTimeZone)
  2. the timezone of the venue (venueTimeZone)

I need to convert the time selected by the user (data.value) to the correct date in the venueTimeZone. For example, if the user is in Americas/New York and they selected 1:30PM on the 20/05/2022, and the venue is in Americas/Los Angeles – the value I am interested in obtaining is 20/05/2022 10:30AM.

This is my attempt, however the timezone itself doesn’t change – I think this is because when I create the userDateTime with moment I don’t specify a time offset, but I’m not sure how to obtain the offset from userTimeZone, whilst accounting for DST.

            const userTimeZone = _.get(
                Intl.DateTimeFormat().resolvedOptions(),
                ['timeZone']
            );

            const venueDateStr = new Date().toLocaleString('en-US', {
                timeZone: venueTimeZone,
            });

            const Date = new Date(restaurantDateStr);
            const venueYear = venueDate.getFullYear();
            const venueMonth = `0${venueDate.getMonth() + 1}`.slice(-2);
            const venueDateOfMonth = `0${venueDate.getDate()}`.slice(-2);

            const userDateTime = createDateAsUTC(
                moment(
                    `${venueDateOfMonth}/${venueMonth}/${venueYear} ${data.value}`,
                    'DD/MM/YYYY hh:mm a'
                ).toDate()
            ).toLocaleString('en-US', { timeZone: venueTimeZone });

Using JS Variables in scripts

I’m writing a function in JS that will iterate through a python list and see if any of the numbers in that list match the parameter that is the input for the function. Here’s the code:

function popup(elementId)
        {
            for (i = 1; i < {{ len_days }} ; i++) {
                if (elementId === {{ days_list[i] }}) {
                    document.getElementById(elementId.toString()).innerHTML = "working"
                    var popup_element = document.getElementById(elementId);
                    popup_element.classList.toggle("show");
                }
            }
        }

In this case {{days_list}} is the python list. I’m able to select the specific index by using [0] or [1], but I want to be able to use [i] to iterate through all the items in this list. Is there a way for me to use the same i as in the JS for loop, or do I have to make it in python?