addEventListener() for touch screens

I do Etch-a-Sketch.

It is one of the functions. It work normally on computer with mouse. But don’t work on touch screens (phone).

mouseSquares.forEach(gridSquares => {

        gridSquares.addEventListener('mouseover', () => {
            
            if (mouseHoveringColor === "yellow") {
                gridSquares.style.backgroundColor = mouseBackgroundColor;   
            } else if (mouseHoveringColor === "randomize") {
                gridSquares.style.backgroundColor = mouseBackgroundColor;
            } else {
                let r = Math.floor(Math.random() * 256);
                let g = Math.floor(Math.random() * 256);
                let b = Math.floor(Math.random() * 256);
                gridSquares.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
            }

        });

        gridSquares.addEventListener('click', () => {
            gridSquares.style.backgroundColor = SQUARESBACKGROUNDCOLOR;
        });

    });

I tried add events touchmove and touchcancel – but it doesn’t work too.

I need both functionality: for computer mouse and for touch screens.

Regex with NAND logic for single characters

Using dashes AND commas in the string shouldn’t be allowed:

123 — ok
1,23 — ok
1-23 — ok
1,2-3 — not ok
1-2-3 — ok

Since the question should contain 220 characters, I’ll add that no popular AI managed to produce the correct result, no matter how I refined the query.

How can I prevent a custom input from re-rendering onChange while also notifying the parent component about this change? [duplicate]

My intention is to create a custom input element that avoids re-rendering whenever the input value changes, but at the same time notifies the parent if the input changes.

Input component:

import { useRef, useEffect, ChangeEvent } from "react";

type props = {
changeFunction?: (e: ChangeEvent<HTMLInputElement>) => void;
};

function TestInput({ changeFunction }: props) {
let inputRef = useRef<HTMLInputElement>(null);

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

function change(e: ChangeEvent<HTMLInputElement>) {
  console.log("Input change", e.target.value);
  if (inputRef.current) inputRef.current.value = e.target.value;
  if (changeFunction) changeFunction(e);
}

return (
  <input
    ref={inputRef}
    type="search"
    id="test"
    name="test"
    autoComplete="off"
    onChange={change}
  />
);
}

export default TestInput;

Parent component:

import { useCallback, useState, ChangeEvent } from "react";
import TestInput from "./Test";

function TestParent() {
  let [value, setValue] = useState("");
  let change = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => setValue(e.target.value),
    []
  );

  return (
    <div>
      <p>Value: {value}</p>
      <TestInput changeFunction={change} />
    </div>
  );
}

export default TestParent;

Despite using useCallback the input component re-renders every time. If we exclude the changeFunction prop this doesn’t happen. What could be the solution?

Here’s a Stack Snippet without the TypeScript parts showing the problem.

const { useState, useEffect, useCallback, useRef } = React;

function TestInput({ changeFunction }) {
  let inputRef = useRef(null);

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

  function change(e) {
    console.log("Input change", e.target.value);
    if (inputRef.current) inputRef.current.value = e.target.value;
    if (changeFunction) changeFunction(e);
  }

  return (
    <input
      ref={inputRef}
      type="search"
      id="test"
      name="test"
      autoComplete="off"
      onChange={change}
    />
  );
}

function TestParent() {
  let [value, setValue] = useState("");
  let change = useCallback(
    (e) => setValue(e.target.value),
    []
  );

  return (
    <div>
      <p>Value: {value}</p>
      <TestInput changeFunction={change} />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<TestParent />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Vue 3 – cannot set a property on the global window object

I am using Vue 3 SFC and trying to create a global property on the window object.

However, I am facing an issue where this property seems to be available only during script execution and becomes undefined immediately after.

For example, the following code correctly outputs ‘Hello World’ in the browser console:

<script setup>
import { onMounted} from 'vue'

onMounted(() => {
  window._MYMSG = 'Hello World';
  console.log(window._MYMSG);
});

</script>

<template>
</template>

But if you type the same line directly in the browser console immediately after executing the script, you get undefined:

console.log(_MYMSG) // returns undefined

It seems like the property exists while the script executes, and gets deleted after. What am I missing?

P.S. The window object in the script is indeed a global window object. If you replace the console.log line with window.alert(window._MYMSG), you will get a proper alert, confirming this is a window object.

Data is not coming at server end

I have created a registration form. So when user filled that data, expected behaviour is, at server business logic should be applied on that data.
Through req field data should come at server. But it is not coming. req.body is empty

Here is my code

Register.jsx

 function Register() {
  const [registerUser, setRegisterUser] = useState({
    username: "",
    email: "",
    password: "",
  });
  const handleClick = async (e) => {
    try {
      e.preventDefault();
      const response = await RegisterUser(registerUser);
      // some code 
  };
}       
 

users.js

import axios from "axios";
axios.defaults.baseURL = "http://localhost:5000";

export const RegisterUser = async (registerUser) => {
  console.log("In RegisterUser =====> ", registerUser);  // getting data properly
  try {
    const response = await axios.post("/api/users/register", registerUser);
    return response.data;
  } catch (error) {
    return error.response.data;
  }
};

server.js

const express = require("express");
const cors = require("cors");
require("dotenv").config();
const app = express();
const dbConfig = require("./Config/dbConfig");
const port = process.env.PORT || 5000;

const server = require("http").createServer(app);

const usersRoute = require("./routes/usersRoutes");

app.use(cors({ origin: "http://localhost:3000" }));

app.use("/api/users", usersRoute);

server.listen(port, () => console.log(`Server running on port ${port}`));      
  

usersRoutes.js

const router = require("express").Router();
const User = require("../models/userModel");

// User Registration
router.post("/register", async (req, res) => {

    if (!req.body)    
       console.log("EMPTY");    // EMPTY is getting printed

  try {
    const user = await User.findOne({ email: req.body.email });
    if (user) {
      return res.send({
        success: false,
        message: "User already exists",
      });
    }
    const newUser = new User(req.body);
    await newUser.save();
    res.send({
      success: true,
      message: "User created successfully",
    });
  } catch (error) {
    res.send({
      message: error.message,
      success: false,
    });
  }
});

module.exports = router;     
 

In above code, I am getting error as :

Cannot read properties of undefined (reading ’email’)

In RegisterUser(), I tried to printed data through

console.log(“In RegisterUser =====> “, registerUser);

and it is coming properly.

But when I try to print data at server side using

if (!req.body)
console.log(“EMPTY”);

it is coming EMPTY.

Why data is not coming at server side ?

How to prevent double click on submit button in chrome

I want to disable submitting form twice. Users often double click on submit button and then form is submitted twice. I already tried following Javascript, but does not work:

const btn = document.querySelector("#buttonid");
btn.addEventListener("dblclick", (e) => {
  e.preventDefault();
});
const button = document.querySelector("#buttonid");
button.addEventListener("click", (e) => {
  document.getElementById("buttonid").disabled = true;
});
$('#buttonid').prop("disabled", true);
<button ondblclick="this.disabled=true;">submit</button>

dynamically added content through js not showing up on netlify

I am trying to make a Spotify clone. I am fetching songs from my local machine. All the songs’ albums are inside the songs folder but when I run this on my local machine it’s working fine while on netlify the dynamically added content like my songs, song names and song time are not showing up.
Here is the link to my deployed project on Netlify
Here is the link to my GitHub repo
Looking like this on Mobile
Looking like this on Netlify
Looking like this on my local machine

Get a warning from Google Page Speed ​Insight about page redirects

I made a script to redirect users who use browsers other than Indonesian. the script runs fine. But when I checked Google Page Speed ​​Insight I got a warning: The page may not be loading as expected because your test URL (https://www.my-website.com/) was redirected to https://www.my-website.com/en/ . Try testing the second URL directly.

how do I create a function so that the script I create will not run if the user is a bot / crawler / google bot, etc.

here is the script

// Mendeteksi bahasa browser pengguna
var userLanguage = navigator.language || navigator.userLanguage;

// Mendapatkan preferensi bahasa pengguna dari localStorage
var preferredLanguage = localStorage.getItem('preferredLanguage');

// Mendapatkan timestamp terakhir dari redirect
var lastRedirectTime = localStorage.getItem('lastRedirectTime');
var currentTime = new Date().getTime();
var oneDay = 24 * 60 * 60 * 1000; // Waktu dalam milidetik untuk 24 jam

// Fungsi untuk melakukan redirect dengan pengecekan waktu
function redirectIfNeeded(url) {
    if (!lastRedirectTime || currentTime - lastRedirectTime > oneDay) {
        localStorage.setItem('lastRedirectTime', currentTime);
        window.location.href = url;
    }
}

// Jika tidak ada preferensi bahasa yang disimpan di localStorage
if (!preferredLanguage) {
    // Jika bahasa pengguna bukan bahasa Indonesia ('id')
    if (userLanguage !== 'id') {
        // Redirect ke halaman bahasa Inggris dengan pengecekan waktu
        redirectIfNeeded("https://www.my-website.com/en");
    }
} else {
    // Jika preferensi bahasa adalah bahasa Indonesia ('id')
    if (preferredLanguage === 'id') {
        // Redirect ke halaman bahasa Indonesia
        window.location.href = "https://www.my-website.com";
    }
}

// Fungsi untuk mengubah bahasa ke bahasa Indonesia dan menyimpan preferensi di localStorage
function changeToIndonesian() {
    localStorage.setItem('preferredLanguage', 'id');
    window.location.href = "https://www.my-website.com";
}

// Fungsi untuk mengubah bahasa ke bahasa Inggris dan menyimpan preferensi di localStorage
function changeToEnglish() {
    localStorage.setItem('preferredLanguage', 'en');
    window.location.href = "https://www.my-website/en";
}

jQuery click event not fired when element clicked

I’ve seen this question asked and answered before but after trying several proposed solutions I still haven’t had any luck.

I have four buttons ( respectively with ID’s “frst, prev, next, last,”) None of them do anything when clicked. Currently my the part of my code that isn’t working looks like so:


const index = ['imgs/1.png', 'imgs/2.png', 'imgs/3.png', 'imgs/4.png', 'imgs/5.png'];

let current = index.length;

$(document).ready(function(){
   $(document).on('click', '#frst', function(){
        current = 1;
        funcUpdate();
    });

    $(document).on('click', '#prev', function(){
        current--;
        funcUpdate();
    });

    $(document).on('click', '#next', function(){
        current++;
            funcUpdate();
    });

    $(document).on('click', '#last', function(){
        current = index.length;
        funcUpdate();
    });

});

The function funcUpdate isn’t getting run, and I’ve also had the value of “current” get logged, and it isn’t changing. funcUpdate just switches out an image src with the index value at current – 1. I decided not to put it here to keep things succinct, and I know it isn’t the problem because when I instead onclick trigger in html, everything works fine.

I’ve also tried $('#ID').click and $('#ID').on('click', function(){});, each in and outside of $(document).ready with no luck.

I bet it’s probably some really obvious error I’ve overlooked but I figured I’d ask anyway.

Issue with LIFF Redirect from Page A to Page B

I’d like to inquire about an issue regarding LIFF (Line Front-end Framework). On Page A, which lacks liff.init, there’s a button that should navigate to Page B (a different URL). Page B, however, does have liff.init initialized.

I’m wondering why, when I click the button on Page A to navigate to Page B, it keeps redirecting back to Page A. Are there any relevant documents or explanations for this behavior? Thank you!

Output List in JSX

I am trying to output a HTML list in JSX.

Here is how I build the array:

let seasonsList = [];

for (var i=0; i < jsonData.data.campaigns.list.length; i++) {
    seasonsList.push(<li key={i}>{jsonData.data.campaigns.list[i].name}</li>);
}

 

When I try to output this list I get nothing inside the ul tags

return (
    <ul>{seasonsList}</ul>
);

How can I output the list of names inside the ul tags?

In angular Rxjs catchError fails with TypeError

I am trying to send post request to create/update user. When I get 400 response, the catchError function fails with

TypeError: You provided an invalid object where a stream was expected.
You can provide an Observable, Promise, ReadableStream, Array,
AsyncIterable, or Iterable.
at createInvalidObservableTypeError (throwUnobservableError.js:2:12)
at innerFrom (innerFrom.js:37:11)
at catchError.js:10:29

My Error response object is,

{
  "isSuccess": false,
  "message": "User with same email already registered.",
  "responseObject": {
    "id": 0,
    "name": "" 
  }
}

My code is,

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

import { environment } from '../../../../environments/environment';

@Injectable({ providedIn: 'root' })
export class CreateUser {
  constructor(private http: HttpClient) {}

  createIcUser(request: object) {
    return this.http
      .post<any>(`${environment.URL}/api/users`, request)
      .pipe(catchError(this.handleError));
  }

  updateIcUser(id: string, request: object) {
    return this.http
      .put<any>(`${environment.URL}/api/users/${id}`, request)
      .pipe(catchError(this.handleError));
  }

  private handleError(errorRes: HttpErrorResponse) {
    console.log(errorRes)
    let errors = { title: errorRes.error.title, details: [] };
    if (
      typeof errorRes.error.errors === 'object' &&
      errorRes.error.errors !== null &&
      Object.keys(errorRes.error.errors).length > 0
    ) {
      errors.details = Object.keys(errorRes.error.errors).map((field) => ({
        field,
        message: errorRes.error.errors[field].join(', '),
      }));
    } else {
      if (errorRes.error.isSuccess === false) {
        errors.title = 'Server Error';
        errors.details.push({
          field: 'error',
          message: errorRes.error.message,
        });
      }
    }

    return throwError(
      () =>
        errors || {
          title: 'An unknown error occurred!',
          details: [
            {
              field: 'error',
              message: errorRes.error.message,
            },
          ],
        }
    );
  }
}

My subscription code is,

let updateUserObs: Observable<any>;
    if (!this.isEditMode) {
      updateUserObs = this.createUserService.createIcUser(
        this.getProperties({ isEditMode: false })
      );
    } else {
      updateUserObs = this.createUserService.updateIcUser(
        this.guid,
        this.getProperties({ isEditMode: true })
      );
    }

    this.subscription = updateUserObs.subscribe({
      next: (resData) => {
        this.selectedIcUser.clear();
        this.router.navigate(['/dashboard/users'], {
          state: {
            id: this.selectedCompany.company.id,
            success: true,
            isEditMode: this.isEditMode,
          },
        });
      },
      error: (errors) => {
        this.showErrorModal = true;
        this.errorData = errors;
        console.error('from subscription', errors);
      },
    });

What wrong with my code. Earlier, it was working fine. But suddenly I am getting this error.

how can we add the function return type in request object in nest js

i want to create a response format serialization for globally so i want to add the function return type in request object. so in the interceptor i can take the return type and apply the serialization. i want to apply the interceptor globally for all the module to commonaly used the global level. so thats why i want to add the function return type in request object

example

@Controller(':breedId/cats')
export class CatsController {
  constructor(
    private readonly CatsService: CatsService,
  ) {}

  @Post()
  @ReturnType(Dto)
   create(
    @Param('breedId', ParseIntPipe) breedId: number,
    @Body() dto: CreateDto,
  ): Promise<CreateDto> {
   return ...   
  }

  @Post('list')
  async findAll(
    @Param('breedId', ParseIntPipe) breedId: number,
    @Body() CreateDto: CreateDto,
  ): Promise<CreateDto[]>  {

   
    return ...;
  }

How to Find element inside iframe by its text in cypress

I’m trying to locate an element within an iframe based on its text using Cypress

Neither of the following methods is not working in order to find or interact with element based on its text:

`

import "cypress-iframe";

cy.iframe('[data-testid="iframe"]').within(() => {
cy.contains('The cost is £500.00.', { timeout: 30000 }).should('be.visible');
});

cy.iframe().contains('The cost is £500.00')
cy.iframe().find('The cost is £500.00')`

Discord.js Interaction has failed

I am trying to create a simple ticketbot for discord, but I ran into an issue that I cannot seem to fix, I have tried several different approaches and adding a deferReply aswell, but whenever the button to create a ticket is clicked, I get the “interaction has failed” error.
I also added error handling to check if there might be another issue related to permission, but there is no console output at all, so i am really unsure on what the error is.

If anyone knows of a way to fix this I would greatly appreciate it.
Below is my code

const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, PermissionsBitField } = require('discord.js');
const { translate } = require('../locales/en.json');

class TicketManager {
    constructor(client) {
        this.client = client;
        this.setupInteractionHandler();
    }

    setupInteractionHandler() {
        this.client.on('interactionCreate', async interaction => {
            if (!interaction.isButton()) return;

            switch (interaction.customId.split('_')[0]) {
                case 'create_ticket':
                    await this.handleTicketCreation(interaction).catch(error => {
                        console.error('Error handling ticket creation:', error);
                        interaction.followUp({ content: translate("ERROR_CREATING_TICKET"), ephemeral: true }).catch(console.error);
                    });
                    break;
                case 'close_ticket':
                    await this.handleTicketClosure(interaction).catch(error => {
                        console.error('Error handling ticket closure:', error);
                        interaction.followUp({ content: translate("ERROR_CLOSING_TICKET"), ephemeral: true }).catch(console.error);
                    });
                    break;
            }
        });
    }

    async handleTicketCreation(interaction) {
        await interaction.deferReply({ ephemeral: true });

        try {
            const supportCategory = interaction.guild.channels.cache.find(c => c.type === ChannelType.GuildCategory && c.name.toLowerCase() === "support");
            if (!supportCategory) {
                console.error('Support category does not exist');
                return interaction.editReply({ content: translate("SUPPORT_CATEGORY_MISSING") });
            }

            if (!interaction.guild.me.permissions.has(PermissionsBitField.Flags.ManageChannels)) {
                console.error('Missing permission to manage channels');
                return interaction.editReply({ content: translate("MISSING_MANAGE_CHANNELS_PERMISSION") });
            }

            const ticketChannel = await interaction.guild.channels.create({
                name: `ticket-${interaction.user.username.toLowerCase()}-${Date.now()}`,
                type: ChannelType.GuildText,
                parent: supportCategory.id,
                permissionOverwrites: this.getPermissionOverwrites(interaction)
            });

            const closeTicketButton = new ButtonBuilder()
                .setCustomId(`close_ticket_${ticketChannel.id}`)
                .setLabel(translate("CLOSE_TICKET"))
                .setStyle(ButtonStyle.Danger);

            const row = new ActionRowBuilder().addComponents(closeTicketButton);
            const embed = new EmbedBuilder()
                .setColor(0x00AE86)
                .setTitle(translate("TICKET_CREATED_TITLE"))
                .setDescription(translate("TICKET_CREATED_DESCRIPTION", { user: interaction.user.username }))
                .setFooter({ text: translate("USER_ID_LABEL") + `: ${interaction.user.id}` });

            await ticketChannel.send({ content: interaction.user.toString(), embeds: , components: [row] });
            await interaction.editReply({ content: translate("TICKET_CREATED_REPLY") });
        } catch (error) {
            console.error('Failed to create ticket:', error);
            throw error;
        }
    }

    async handleTicketClosure(interaction) {
        try {
            if (!interaction.guild.me.permissions.has(PermissionsBitField.Flags.ManageChannels)) {
                console.error('Missing permission to manage channels');
                throw new Error(translate("MISSING_MANAGE_CHANNELS_PERMISSION"));
            }

            const ticketChannel = interaction.channel;
            await ticketChannel.delete();
        } catch (error) {
            console.error('Failed to close ticket:', error);
            throw error;
        }
    }

    getPermissionOverwrites(interaction) {
        return [
            {
                id: interaction.guild.id,
                deny: [PermissionsBitField.Flags.ViewChannel]
            },
            {
                id: interaction.user.id,
                allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.SendMessages]
            },
            {
                id: interaction.guild.roles.cache.find(r => r.name === "Administrator").id,
                allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.ManageMessages]
            }
        ];
    }
}

module.exports = TicketManager;