How to send the user programmatically to another route?

Given is a VueJS 3 application, based on Quasar and I am struggling to use the Router programmatically.

The issue is described best like this:

1. The Problem

When I push the User to another route, only the URL in the browser will be updated, but the corresponding Component will not get rendered.
I have to manually refresh the web page in the Webbrowser in order to get the corresponding component rendered properly.

2. Code

I have published a full working example on GitHub: https://github.com/itinance/quasar-
router-bug

The router is configured in history-mode, but this doesn’t matter as the issue appears also in the hash-mode.

Here are my routes:

import { RouteRecordRaw } from 'vue-router';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [{ path: '', component: () => import('pages/IndexPage.vue') }],
  },

  {
    path: '/test',
    name: 'test',
    component: () => import('layouts/MainLayout.vue'),
    children: [{ path: '', component: () => import('pages/TestPage.vue') }],
  },

  // Always leave this as last one,
  // but you can also remove it
  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];

export default routes;

Here is my Index-Component, that contains a button where I want to send the user programmatically to another page:

<template>
  <q-page class="row items-center justify-evenly">

    <div class="q-pa-md example-row-equal-width">
      <div class="row">
        <div>INDEX PAGE</div>
      </div>


      <div class="row">
        <div>
          In order to navigate to the test page, you need to manually reload the page after clicking the button.
          Otherwise, only a white page will be rendered.

          <q-btn align="left" class="btn-fixed-width" color="primary" label="Go to test page" @click="doRedirect"/>
        </div>
      </div>


    </div>
  </q-page>
</template>

<script lang="ts">
import {Todo, Meta} from 'components/models';
import ExampleComponent from 'components/ExampleComponent.vue';
import {defineComponent, ref} from 'vue';
import {dom} from 'quasar';
import {useRouter} from 'vue-router';

export default defineComponent({
  name: 'IndexPage',
  computed: {
    dom() {
      return dom
    }
  },
  components: {},
  setup() {

    const router = useRouter();

    const doRedirect = () => {
      console.log('doRedirect');
      router.push({name: 'test'});
    }
    return {doRedirect};
  }
});
</script>

And this is the test-component, which is the target component where I want to use send:

<template>
  <q-page class="row items-center justify-evenly">

    <div class="q-pa-md example-row-equal-width">
      <div>
        TEST PAGE

        this will only be rendered after manual page-reload

      </div>
    </div>
  </q-page>
</template>

<script lang="ts">
import { Todo, Meta } from 'components/models';
import ExampleComponent from 'components/ExampleComponent.vue';
import { defineComponent, ref } from 'vue';

export default defineComponent({
  name: 'TestPage',
  setup () {
    return { };
  }
});
</script>
  1. What happens instead?

3.1 This is the index page, containing the button that shall send the user to another page:

enter image description here

3.2. When I click on the Button, the URL will be updated correctly but the test-component won’t get rendered at all:

enter image description here

3.3. But when I refresh the web browser now manually (or navigate to that particular URL), it will render the test component:

enter image description here

#4. Question

What am I doing wrong? How can I programmatically send the user to the test-page so that not only will the URL be updated but also the component will get rendered automatically, once the URL has changed?

As already mentioned, I also published a small test project that makes the described issue reproducible: https://github.com/itinance/quasar-router-bug

Chrome seekbar issue when recording a video and playing it via RecordRTC

I am using RecordRTC to record and play the video in my webpage however after recording the video and trying to play it back on Chrome or Edge, the seekbar is at the end and eventually after sometime it goes back to the time it is playing at.

      async startRecording() {
    try {
      this.recordRTC = RecordRTC(this.mediaStream, {type: 'video'});
      this.recordRTC.startRecording();
    } catch (error) {
      alert('Access for microphone and webcam not granted');
    }
  }

 stopRecording() {
    this.recordRTC.stopRecording(() => {
      this.stopStream();
      const blob = this.recordRTC.getBlob();
      this.videoURL = URL.createObjectURL(blob);
      this.recordedVideoElement.nativeElement.src = this.videoURL;
    });
  }

         <video #recordedVideo>
            <source [src]="this.videoURL">
          </video>      async startRecording() {
    try {
      this.recordRTC = RecordRTC(this.mediaStream, {type: 'video'});
      this.recordRTC.startRecording();
    } catch (error) {
      alert('Access for microphone and webcam not granted');
    }
  }

<video #recordedVideo>
            <source [src]="this.videoURL">
          </video>

However on Firefox there is no such issue, am I doing something wrong or do I need to process the video in some form? Any help is appreciated.

Fetch API Url with Arguments [duplicate]

I have this [working] HTML/Javascript code to fetch data from a json API.

function getElement(id) {
  return document.getElementById(id);
}

fetch('https://api-url.tld')
.then(res => res.json()
.then(json => {
  getElement('total_clicks').innerText = json["stats"]["total_clicks"];
}));

But now I want to use a different API, with different requirements. I can retrieve the json output with the following curl command:

curl -X 'GET' 
  'https://api-url.tld' 
  -H 'accept: application/json' 
  -H 'X-Api-Key: APIKEY'

This is an example output of it:

{
  "visits": {
    "nonOrphanVisits": {
      "total": 0,
      "nonBots": 0,
      "bots": 0
    },
    "data": 0,
  }
}

What should the first code look like so that I get the same result? At the end of "nonOrphanVisits" -> "total": 0 should be inserted here in getElement('total_clicks').innerText.

Thank you for Answers!

NextAuth register redirects to /api/auth/error

I’ve been following one guide from YT about using Next.js 13 to build E-Shop, and made it to routes. 10 minutes in and I’m stuck. So I dont know. I’m new to this, could someone please hep me

Here’s what I have:

pagesapiauth[…nextauth].ts

import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import CredentialsProvider from "next-auth/providers/credentials"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import prisma from "@/libs/prismadb"
import bcrypt from "bcrypt"

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
    CredentialsProvider({
        name: 'credentials',
        credentials:{
            email:{
                label: 'email',
                type: 'text'
            },
            password: {
                label: 'password',
                type: 'password'
            },
        },
        async authorize(credentials){
            if(!credentials?.email || !credentials?.password){
                throw new Error('Invalid email or password')
            }

            const user = await prisma.user.findUnique({
                where: {email: credentials.email},
            })

            if(!user || !user?.hashedPassword){
                throw new Error('Invalid email or password')
            }

            const isCorrectPassworg = await bcrypt.compare(
                credentials.password,
                user.hashedPassword
            )

            if(!isCorrectPassworg){
                throw new Error('Invalid email or password') 
            }

            return user
        }
    })
  ],

  pages:{
    signIn: "/login",
  },
  debug: process.env.NODE_ENV === 'development',
  session: {
    strategy:'jwt',
  },
  secret: process.env.NEXTAUTH_SECRET
})

appregisterRegisterForm.tsx

"use client";

import { useState } from "react";
import Input from "../components/inputs/input";
import { FieldValues, SubmitHandler, useForm } from "react-hook-form";
import Button from "../components/Button";
import Link from "next/link";
import { AiOutlineGoogle } from "react-icons/ai";
import axios from "axios";
import { signIn } from "next-auth/react";
import { toast } from "react-hot-toast";
import { useRouter } from "next/navigation";

const RegisterForm = () => {
  const [isLoading, setIsLoading] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FieldValues>({
    defaultValues: {
      name: "",
      email: "",
      password: "",
    },
  });

  const router = useRouter();

  const onSubmit: SubmitHandler<FieldValues> = (data) => {
    setIsLoading(true);

    axios
      .post("/api/register", data)
      .then(() => {
        toast.success("Account created");

        signIn("credentials", {
          email: data.email,
          password: data.password,
          redirect: false,
        }).then((callback) => {
          if (callback?.ok) {
            router.push("/my-characters");
            router.refresh();
            toast.success("Logged In");
          }

          if (callback?.error) {
            toast.error(callback.error);
          }
        });
      })
      .catch(() => {
        toast.error("Something went wrong");
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return (
    <>
      <h1 className="flex flex-col items-center text-3xl font-bold text-slate-700">
        Sign Up
      </h1>
      <Button
        outline
        label="Sign up with Google"
        icon={AiOutlineGoogle}
        onClick={() => {}}
      />
      <hr className="bg-slate-300 w-full h-px" />
      <Input
        id="name"
        label="Name"
        disabled={isLoading}
        register={register}
        errors={errors}
        required
      />
      <Input
        id="email"
        label="Email"
        disabled={isLoading}
        register={register}
        errors={errors}
        required
      />
      <Input
        id="Password"
        label="Password"
        disabled={isLoading}
        register={register}
        errors={errors}
        required
        type="password"
      />
      <Button
        label={isLoading ? "Loading" : "Sign Up"}
        onClick={handleSubmit(onSubmit)}
      />
      <p className="text-sm">
        Already have an account?{" "}
        <Link className="underline" href="/login">
          Log In
        </Link>
      </p>
    </>
  );
};

export default RegisterForm;

appapiregisterroute.ts

import bcrypt from "bcrypt"
import prisma from "@/libs/prismadb"
import { NextResponse } from "next/server"

export async function POST(request: Request){
    const body = await request.json()
    const {name, email, password} = body

    const hashedPassword = await bcrypt.hash(password, 10)

    const user = await prisma.user.create({
        data:{
        name, 
        email, 
        hashedPassword
        },
    })

    return NextResponse.json(user)
}

libsprismadb.ts

import { PrismaClient } from '@prisma/client'

declare global{
    var prisma: PrismaClient | undefined
}

const client = globalThis.prisma || new PrismaClient()

if(process.env.NODE_ENV !== "production") globalThis.prisma = client;

export default client;

Guy from video tries registration and it automatically redirects him to the page he specified but when I try, I get an error. So after seing this problem I tried to open link in Incognito Mode(did nothing). Path to […nextauth].ts is correct(checked 5 times). I’ve also checked my DB and everything got there correctly. In Chrome console I have this error GET http://localhost:3000/api/auth/error 404 (Not Found)

Clipboard API and HTML for email signature generator

I’m building a simple email signature generator and I’ve run into the deprecated document.execCommand('copy') method.

I’ve got a div that holds the styled table for the footer, but when I run my try block and paste it into Outlook, the output is not what I expect.

const contentToCopy = document.getElementById(contentElId);
const range = new Range();
range.selectNode(contentToCopy);
window.getSelection().addRange(range);
// document.execCommand('copy');
await navigator.clipboard.writeText(contentToCopy);
window.getSelection().removeAllRanges();

I’m not sure what to pass into the writeText method.

  1. If I pass contentToCopy.innerText I don’t get the anchor + image
  2. If I pass contentToCopy.innerHTML the HTML is escaped when I paste it into outlook.
  3. If I pass contentToCopy.textContent I get a bunch of weird spacing and no html (expected this)

When I trigger a copy myself (Cmd + C) and paste the result into Outlook, it works fine. How can I mirror that data with JS?

Additionally, I’ve seen this question and answer that says

“instruct the browser to pass the text in as text/html when the copy event fires.”

However, I’m not sure how to accomplish this with the clipboard API.


If it helps, The contentToCopy in this case is a a div with a nested html table

<div id='contentToCopy'>
<table style="text-align: left; font-size: 14px; border:0; border-collapse: collapse; line-height: 25px;" cellpadding="0" cellspacing="0">
                <tbody style="border:0;">
                    <tr style="border:0;">
                        <td rowspan="6" style="border:0; padding-right:20px;">
                            <a href="https://www.choctawnation.com">
                                <img src="https://associates.choctawnation.com/wp-content/themes/bootscore-main/img/logo.png" width="170px" />
                            </a>
                        </td>
                        <td colspan="5" style="border:0;"><span style="border:0;" id="firstNameOutput">First Name</span> <span style="border:0;" id="lastNameOutput">Last
                                Name</span>
                        </td>
                    </tr>
                    <tr style="border:0;">
                        <td colspan="5" style="border:0;"><span style="border:0;" id="titleOutput">Job
                                Position</span> | <span id="departmentOutput" style="border:0;">Department</span>
                        </td>
                    </tr>
                    <tr style="border:0;">
                        <td colspan="5" style="border:0;">
                            <a href="tel:800-522-6170" id="mobileOutput">
                                <span style="border:0;">
                                    800-522-6170
                                </span>
                            </a>
                            <span id="mobileDivider" style="display: none;">|</span>
                            <a href="" id="desktopOutput">
                            </a>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="5" style="border:0;">
                            <a id="emailOutput" href="mailto:[email protected]"><span style="border:0;">[email protected]</span>
                            </a>
                        </td>
                    </tr>
                </tbody>
            </table>
            <table style="text-align: left; font-size: 14px; border:0; border-collapse: collapse; line-height: 25px; padding-top:10px;" cellpadding="0" cellspacing="0">
                <tr>
                    <td rowspan="6" style="border:0;">
                        <a id="buttonOutput"><span style="border:0;"></span>
                        </a>
                    </td>
                </tr>
            </table>
            <table style="text-align: left; font-size: 14px; border:0; border-collapse: collapse; line-height: 25px; padding-top:10px;" cellpadding="0" cellspacing="0">
                <tbody id="disclaimerOutput" class="disclaimerText">
                </tbody>
            </table>
</div>

js how to use dynamic ID from php array in js script

I search directories and I have folder names (about 30). I display them as links, but I would like to have a folder icon in front of each folder name. When I click on folder A, for example, icon1 should change to icon2. When I click on folder A again, icon2 should return to icon1. During this time, the icons of other folders do not change (after one click always I have: 1 icon2 and 29 icon1). For example, when the icon next to the folder A is icon2 and I click on folder B, the icon next to folder A will change (come back) to icon1 and the icon next to folder B will change from icon1 to icon2. The icon and its folder are a one button together.

My script is working with static ID (id=”myB”) of link but with dynamic (from array – $file) not. I tried to use a variable from php to enter the value in js but everything blocked.

this is working script for one link

    <A href="test.php" target="main" id="myB"><img id="myImg" src="folder.png"> folder name </a><BR>
    
<script>
    
    // JavaScript code
    const myB = "myB";
    const myImg = document.getElementById("myImg");
    const myButton = document.getElementById("myB");
    
    myButton.addEventListener("click", function() {
      if (myImg.src.endsWith("folder.png")) {
        myImg.src = "folder_open.png";
      } else {
        myImg.src = "folder.png";
      }
    });
    
    </script>

my dynamic names of folders and dynamic links

foreach ($file_info_all as $file){

   echo ' &nbsp;  <A href="index-main.php?cat=' . $file . '" target="main" id="myB"><img id="myImg" src="folder.png"> &nbsp; ' . $file . '</A><br>';
   
    }

Google maps API not working from Safari 2023

a request from chrome is working perfectly while I get this on Safari, with nothing changing, just the browser. The site is running on https entirely. Changed from fetch to axios with the same results. The key has a restriction on IP.

{
  "data": {
    "error_message": "This IP, site or mobile application is not authorized to use this API key. Request received from IP address XX.XX.XX.XX, with referer: https://XXXX/",
    "results": [],
    "status": "REQUEST_DENIED"
  },
  "status": 200,
  "statusText": "",
  "headers": {
    "cache-control": "no-cache, must-revalidate",
    "content-length": "214",
    "content-type": "application/json; charset=UTF-8",
    "expires": "Fri, 01 Jan 1990 00:00:00 GMT",
    "pragma": "no-cache"
  },
  "config": {
    "transitional": {
      "silentJSONParsing": true,
      "forcedJSONParsing": true,
      "clarifyTimeoutError": false
    },
    "adapter": [
      "xhr",
      "http"
    ],
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "maxBodyLength": -1,
    "env": {},
    "headers": {
      "Accept": "application/json, text/plain, */*"
    },
    "method": "get",
    "url": "https://maps.googleapis.com/maps/api/geocode/json?latlng=XX.790558469393645,-XX.60082901146109&key=XXXX"
  },
  "request": {}
}

Is it possible to target/run a specific js function through Docker or command line in general?

I am in the process of moving some code functionality inside a AWS batch job which I need to manually run to test before deploying. The handler function inside the js file currently is not targeted and so does not run – (when using a lambda, this function was targeted and ran each time).

Currently I do not want to change the js file to manually run the function each time, rather change the command to somehow target the function – not sure if this is even possible.

This is the command to run the file inside Batch/Docker:

CMD ["node","index.js"]

This is the function def inside the js file:

async function main(event, context)

Any recommendations would be appreciated!

Firestore Connection Issues and Unverified App Check Requests in Firebase Web App

Problem:
I’m experiencing consistent issues with Firebase Firestore in my web application. Although authentication processes succeed (users are created in Firebase Auth), attempts to write to Firestore consistently fail with the following errors:

[Warning] Firestore (10.7.0): Connection - "WebChannel transport errored:" – ir {...}
[Error] Firestore (10.7.0): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=unavailable]: The operation could not be completed...
[Error] Error checking referral code uniqueness: – FirebaseError: [code=unavailable]: Failed to get document because the client is offline...
[Error] Error in signup process: – FirebaseError: [code=unavailable]: Failed to get document because the client is offline...

I’m not sure why the client would be offline.

Additionally, I’m encountering CORS-related errors, but this only happened while I was typing this up and I’m not sure what happened:

[Error] Cancelled load to https://www.gstatic.com/recaptcha/releases/.../styles__ltr.css because it violates the resource's Cross-Origin-Resource-Policy response header.

I’m not sure what triggered that either, because I don’t have anything related to recaptcha in my code anywhere except for my site key and the script tags for app check.

Context and Troubleshooting Steps:

  1. This issue started occurring after attempting to implement Firebase App Check and reCAPTCHA, along with updating Firebase SDK from 9.6.10 to 10.7.0 and using modules instead of the global namespace. I reverted to using Firebase 9.6.10 and the global namespace instead of the modular approach, but the issue persists. I then updated back to 10.7.0 while using the global namespace and the issue still persists.

  2. App Check is set up in the Firebase console but not enforced. It showed all requests as unverified, then as verified, back to unverified, and then back to verified without any changes on my side.

  3. In reCAPTCHA, the requests are not marked as suspicious. But for some reason, requests are not being detected there anymore, it was jut requests from yesterday before I was really keeping track of what was going on.

  4. I thought CORS might be an issue, but there were no CORS issues before implementing App Check and reCAPTCHA.

  5. The issue occurs both on localhost and my deployed domain. Both are defined in Firebase and reCAPTCHA.

  6. Firebase Firestore rules have not been altered since the implementation was working correctly.

  7. Tested on different Wi-Fi networks and in incognito mode in a different browser.

  8. I also thought that maybe lite server wasn’t able to handle it, so I moved to Vite and the errors are still happening in my dev environment.

  9. I have verified all my keys and stuff are correct

Firebase Configuration:
Here’s how I’m initializing Firebase in my web app:

const firebaseConfig = {
  apiKey: "mykey",
  authDomain: "myauthdomain",
  projectId: "myprojectID",
  storageBucket: "mystoragebucket",
  messagingSenderId: "mysenderID",
  appId: "myappid",
  measurementId: "mymeasurementID"
};

firebase.initializeApp(firebaseConfig);
firebase.appCheck().activate('mysitekey', true);

HTML Script Tags:

<script src="https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js" defer></script>
<!-- Additional Firebase service scripts -->
<script src="scripts/firebase.js" defer></script>
<!-- Additional custom scripts -->

Code Causing Errors:
The following script triggers functions that throw errors related to Firestore:

function createUserAccount(email, password, referralCode = "") {
    firebase.auth().createUserWithEmailAndPassword(email, password)
        .then((userCredential) => {
            console.log("User created with Firebase Auth, User ID:", userCredential.user.uid);
            const userId = userCredential.user.uid;

            return createUniqueReferralCode().then(newReferralCode => {
                console.log("Generated Unique Referral Code:", newReferralCode);

                // Create a user document in 'users' collection
                const userRef = firebase.firestore().doc('users/' + userId);
                userRef.set({
                    email: email,
                    referralsCount: 0
                });

                // Create a document in 'referralCodes' collection
                return firebase.firestore().collection('referralCodes').doc(newReferralCode).set({
                    ownerId: userId
                });
            });
        })
        .then(() => {
            // Call Cloud Function to update the referrer count
            if (referralCode) {
                return updateReferrerCountCloudFunction(referralCode);
            }
        })
        .then(() => {
            console.log("Redirecting to index.html");
            window.location.href = 'index.html'; // Redirect on successful signup
        })
        .catch((error) => {
            console.error("Error in signup process: ", error);
            document.getElementById('signup-error').innerText = error.message;
        });
}

Observations:
Users are consistently created in Firebase Auth.
Firestore document creation fails every time.
Test signups authenticate users but fail to create documents in Firestore.
Reverting back to the commit before this all started happening still has the issue.
There was a time when instead of failing immediately, it just timed out after 10 seconds. I don’t know what I did to make that happen though, and it hasn’t happened again.

Any insight is appreciated.

How can I programmatically send the user to another page?

Given is a VueJS 3 application (based on Quasar, which is VueJS under the hood).

I want to send the user programmatically to another page.

My router looks like this:

  {
    path: '/ask',
    name: 'ask',
    component: () => import('layouts/QuestionLayout.vue'),
    children: [{ path: '', component: () => import('pages/QuestionPage.vue') }],
  },
  {
    path: '/',
    name: 'home',
    component: () => import('layouts/MainLayout.vue'),
    children: [

When I use

router.push('ask')

or

router.push({name: 'ask')}

only the URL in the Webbrowser will change to the corresponding URL, but its component will not get loaded. Instead, I see an error message in the Browser Console;

enter image description here

I need first to hard-refresh the browser in order to get the page reloaded that belongs to the URL that has been set with router.push.

I also tried window.location.href='/ask', but window is not defined anymore in a VueJS application.

With jQuery and plain vanilla javascript, this has never been a problem. How to do that in 2023?

What’s wrong with my code? My to do list don’t work (pt-br)

My to-do list doesn’t work the way I want it to. The error is in the part of clicking on finish a task, it finishes right but after that I can’t finish any more. I don’t know why this is. In addition, the “finish” starts with the last items, I need help with these two problems.

One finished task
Two finished tasks

html:

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Minhas Tarefas Escolares</title>
</head>

<body>
    <h1 id="titulo">MTE - Minhas Tarefas Escolares</h1>
    <p id="detalhes"></p>

    <div class="lista-tarefas">
        <input type="text" id="tarefa" placeholder="Adicione uma tarefa">
        <input type="button" value="Adicionar" id="adicionar">
        <h2>Tarefas Pendentes</h2>
        <ul id="tarefas">

        </ul>
        <br>
        <br>
        <h2>Tarefas Finalizadas</h2>
        <ul id="finalizadas">

        </ul>
    </div>







    <script type="text/javascript" src="script.js"></script>
</body>

</html>

Script:

const tarefaInput = document.getElementById("tarefa");
const btnAdc = document.getElementById("adicionar");
const listaTarefas = document.getElementById("tarefas");
const listaFinalizadas = document.getElementById("finalizadas")
btnAdc.addEventListener("click", adicionarTarefa);
tarefaInput.addEventListener("keypress", function (e) {
    if (e.key === "Enter") {
        adicionarTarefa();
    }
});
function adicionarTarefa() {
    const tarefaTexto = tarefaInput.value;
    if (tarefaTexto.trim() !== "") {
        const novaTarefa = document.createElement("li");
        novaTarefa.innerHTML = `
          ${tarefaTexto} <button class="excluir">Excluir</button> <button class="finalizar">Finalizar</button>
      `;
        listaTarefas.appendChild(novaTarefa);
        tarefaInput.value = "";

    }
    listaFinalizadas.addEventListener('mouseout', function (e) {
        if (e.target.classList.contains('finalizar')) {
            this.innerHTML = `${tarefaTexto} <button class="excluir">Excluir</button>` //não tá funcionando!!
            this.style.color ='green'
        }
    })
}


listaTarefas.addEventListener("click", function (e) {
    if (e.target.classList.contains("excluir")) {
        e.target.parentElement.remove();
    }
    if (e.target.classList.contains("finalizar")) {
        listaFinalizadas.appendChild(e.target.parentElement)
    }
});

listaFinalizadas.addEventListener("click", function (e) {
    if (e.target.classList.contains("excluir")) {
        e.target.parentElement.remove()
    }

    
})

I tried to change the way I declared the variables, the functions, but none of it worked.

How can i redirect users with onClick and useNavigate functions in react

I’m trying to make this handleDetails(id) function make the user navigate to a note on my progam passing the id of the note as parameter so the back-end can redirect him to the note based on the note_id, but the onClick function is not working
enter image description here

i already tried a lot of things, like putting a useEffect on it somehow, already did some tests like put a console.log on id, and worked fine, seems like the problem is something is not letting onClick function works and redirect me to the /moviePreview/id for some reason

How to use keycodes in an array to filter which keys are taken as input within a ‘keyup’ event listener?

I am trying to build a wordle clone, but I am running into issues when trying to filter out only the alphabet to be taken as keyboard inputs for the game.

Currently I have a Keyboard container that contains each row (of class ‘row’) of keys (of class ‘key’) and a start to a JS file that I cannot seem to move forwards in:

// Keyboard
// Listen for key being released
let key_codes = [81,87,69,82,84,89,85,73,79,80,
                  65,83,68,70,71,72,74,75,76,
                  13,90,88,67,86,66,78,77,8];
document.addEventListener('keyup', (e) => {
    if (e.keyCode in key_codes) {
        console.log(e.keyCode);
    }
});

I have made a list of all the acceptable keycodes for the game, and have tried to add an event listener to watch for keys being released but when I check ‘if (e.keyCode in key_codes)’ I don’t get an output when I should be.

I have checked the types of the list elements and the keyCodes (they match) and have tried printing ‘e.keyCode’ before that if statement, and it correctly prints whichever key I press.

I may be missing something obvious here but somehow I am unable to figure this one out for myself.

Why is the hidden attribute not working on the picture element in next.js?

I have a picture element in my component tree in a Next.js application and I am trying to use the hidden attribute on it, but it doesn’t work, all the images are still completely visible and there’s no hidden attribute when inspecting them in the browser.

The component is:

export function MemberPicture({
  member,
  active,
  id,
}: {
  member: Member;
  active: boolean;
  id: string;
}) {  

  return (
    <picture hidden={!active}>
      <source srcSet={member.images.webp} type="image/webp" />
      <Image
        src={member.images.png}
        alt={member.imageAlt}
        width="445"
        height="445"
        id={id}
        className={classnames(
          pageStyles.image,
        )}
      />
    </picture>
  );
}

I’ve tried to set the hidden attribute on all the elements inside the picture and on the picture itself using a literal boolean value of true, but it doesn’t work either.

<picture hidden={true}>
      <source srcSet={member.images.webp} type="image/webp" hidden={true} />
      <Image
        src={member.images.png}
        alt={member.imageAlt}
        width="445"
        height="445"
        id={id}
        className={classnames(
          pageStyles.image,
        )}
        hidden={true}
      />
    </picture>

The component is being used as shown:

{crew.map((member, index) => {
  return (
    <MemberPicture
      id={imagesIds[index]}
      active={index === selectedMemberIndex}
      member={member}
    />
  );
})}

Its parent’s styles and its styles are:

.imageWrapper {
  grid-area: image;
  max-width: 100%;
}

@media (min-width: 50em) and (orientation: landscape) {
  .imageWrapper {
    grid-column: span 2;
    max-width: 90%;
  }
}

.image {
  max-width: 100%;
}

@media (max-width: 35em) {
  .image {
    max-height: 320px;
  }
}

I am going to use the display property set to none as the hidden attribute is not working, but I still would like to know why setting that attribute does not work at all.

Can someone tell me where my logic is missing?

I am attempting to create a new array of object with an id, siteId, and name. However, based on my logic i am getting a siteid of 1,1,2,3. On the second office value it is incrementing the site Id, although it needs to have a siteId of 2.

var data = [["Jims Burgers", "Hallway", "6209", "Yes", "None", "Occupancy Sensors"],
            ["Jims Burgers", "Office", "6209", "Yes", "None", "Occupancy Sensors"],
            ["Johns Burgers", "Hallway", "6209", "Yes", "None", "Occupancy Sensors"],
            ["Johns Burgers", "Office", "6209", "Yes", "None", "Occupancy Sensors"]]
var siteNames = []
var areaNames= []
var id = 0
data.forEach(function (d) {
  const dm = d.filter((n) => n);
  if(dm.length === 6) {
     
    if(areaNames.find(({name}) => name === dm[1])){
      siteId +=1
      id += 1
      areaNames.push({id: id, siteId: siteId, name: dm[1]})
    }

    if(!areaNames.find(({name}) => name === dm[1])){
      id += 1
      areaNames.push({id: id, siteId: siteId, name: dm[1]})
     
    }  

    if(!siteNames.find(({ name }) => name === dm[0])) {
      siteNames.push({ name: dm[0], id: siteId });
    }
  }
    
});