eventListener target incorrect when clicking on div inside of grid

I have an event listener attached to a wrapper element that checks e.target to see if it contains a class im looking for. If it does then the payload of the rest of the callback function goes off. The target is a div inside of a grid and for some reason if you click on the div while moving your mouse too fast, the e.target becomes the grid itself instead of the div I clicked on.

Is there any way to ensure that e.target is the div inside of the grid, instead of the grid, even while moving mouse quickly?

Javascript:

wrapper.addEventListener('click', function (e) {
    const btn = e.target.closest(`.myClass`)
    if (!btn) return
    // callback function stuff
})

HTML:

<div class="wrapper">
    <div class="grid">
        <div class="myClass"></div>
    </div>
</div>

name21517 function in JS

Today I came across some really strange functions while coding JS in an ASP.NET Razor Page in VS.
The function I found is name21517 but there are a few other functions starting with “name” and then some number. Does anyone know where they come from and what they do?

I haven’t found anything on the internet and I also can’t inspect them in VS.

What can be the reason for site not fully loading on mobile some of the time in both Chrome and Safari?

I have a very weird issue happening, SOME of the time on mobile. It works fine on desktop.
I know that is a weird thing to say, but hear me out. For me, the site has been working fine in iOS Chrome and Safari for the past day, but before that, I experienced the issue as well.

I’ve sent this to about 10 people, some of them web devs, some of them just average joes. All of them were asked to view them in incognito / private browsing.

Sometimes, the website loads fully, sometimes, only the first section loads. Sometimes, it’s just a white screen that loads after two minutes. Sometimes the site just turns partially black, which can’t be explained by the CSS.

The website uses bootstrap, animate.css, and wow.js amongst other things, that I thought maybe causing the issue, but even commenting them out, and some parts of the css has not been successful as of yet.

One of the most pressing issues is, that since I have not been able to replicate the issue on my end, I have no idea as to how to fix it.

The console error log is empty. The WordPress debug is also empty.

So without further ado, the staging website with the issue can be viewed here: https://test10.webkliens.hu/

If anyone can suggest what could be the reason, it would be really appreciated.

Thanks!

Seeing which page you are on (React)

I am working on a frondend mentor challenge that lists what page you are on next to the navbar.
navbar example

The horizontal home div is what I am having trouble with. If you are on the portfolio page, about page, it should say portfolio and about, etc.

import React from 'react'
import './Navbar.css'
import logo from '../../assets/logo.svg'

export default function Navbar({page, setPage}) {
  return (
    <div className='navbar'>
      <div className='current-page'>{page}</div>
      <a href="/" className='home-btn' onClick={() => setPage('home')}>
        {/* <button>Home</button> */}
        <img src={logo} alt="logo" />
      </a>
      <a href="/portfolio" className='port-btn' onClick={() => setPage('Portfolio')}>
        <button className='btn-port'>Portfolio</button>
      </a>
      <a href="/about" className='about-btn' onClick={() => setPage('About Us')}>
        <button className='btn-about'>About Us</button>
      </a>
      <a href="/contact" className='contact-btn' onClick={() => setPage('Contact')}>
        <button className='btn-contact'>Contact</button>
      </a>
    </div>
  )
}

It tried to use a prop and the onClick attribute to tell which page it was on, but it only showed up briefly while the button was currently being clicked. Does anyone else have another solution where the div will stay the same while I am on that page?

Here is my github repository if needed:(https://github.com/pidgebean/arch-studio-react )

Unexpected token ‘T’, “TypeError:”… is not valid JSON with Nextjs

I use Next.js and I’m just trying to add data to the server normally using the fetch method and thunk, but I get this error:

Unexpected token 'T', "TypeError:"... is not valid JSON

Here addBooksForm.jsx file Code:

import React, {useRef} from 'react'
import { useDispatch } from 'react-redux'
import { insertBook } from '@/app/redux/Features/bookSlice'
function addBooksForm() {

  //ref
  const title = useRef(null);
  const img = useRef(null);
  const descripition = useRef(null);
  const bookLinke = useRef(null);
  
  const dispatch = useDispatch();
  const handelSubmit =(e)=>{
    e.preventDefault()
    const data = {
      name: title.current.value,
      photo: img.current.value,
      des: descripition.current.value,
      link: bookLinke.current.value,
      
    };
    dispatch(insertBook(data))
    title.current.value = null;
    img.current.value = null;
    descripition.current.value = null;
    bookLinke.current.value = null;
    
  }

  return (
  
    <div className="w-full  px-4 bg-white ">
    <div className="max-w-[700px] mx-auto">
      <div className="w-full shadow-xl flex flex-col p-4 my-8 rounded-lg ">
        <h2 className="text-2xl font-bold text-center py-4">Insert Book</h2>
        <form onSubmit={handelSubmit}>
          <div className="mb-6">
            <label className="block mb-2 text-l font-medium text-gray-900">
              Title
            </label>
            <input
              type="text"
              className="block w-full p-4 mb-4 text-gray-900 border border-gray-300 rounded-lg bg-gray-50 sm:text-md "
              ref={title}
              required
            ></input>
            <label className="block mb-2 text-l font-medium text-gray-900">
            Linke of image
          </label>
          <input
            type="url"
            className="block w-full p-4 mb-4 text-gray-900 border border-gray-300 rounded-lg bg-gray-50 sm:text-md "
            ref={img}
            required
          ></input>
            <label className="block mb-2 text-sm font-medium text-gray-900 ">
              Description
            </label>
            <textarea
              
              rows={4}
              className="block p-2.5 w-full text-sm mb-4 text-gray-900 bg-gray-50 rounded-lg border border-gray-300"
              
              ref={descripition}
              required
            ></textarea>
            <label className="block mb-2 text-l font-medium text-gray-900">
            Linke of book
          </label>
          <input
            type="url"
            className="block w-full p-4 mb-4 text-gray-900 border border-gray-300 rounded-lg bg-gray-50 sm:text-md "
            ref={bookLinke}
            required
          ></input>
            <button
              type="submit"
              className="text-white bg-[#BDA175] hover:bg-black disabled:bg-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2" 
            >
              Submit
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
      
  )
}

export default addBooksForm

here is bookSlice.js file Code:

"use client";
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

export const insertBook = createAsyncThunk(
  "book/insertBook",
  async (bookData, thunkAPI) => {
    const { rejectWithValue } = thunkAPI;

    try {
      const res = await fetch("http://localhost:3005/books", {
        method: "POST",
        body: JSON.stringify(bookData),
        headers: {
          "Content-type": "application/json; charset=UTF-8",
        },
      });
      const data = await res.json();
      return data;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

const bookSlice = createSlice({
  name: "book",
  initialState: { books: [], isLoading: false, error: null },
  reducers: {},
  extraReducers: (builder) => {
   
      // INSERT BOOK
      builder.addCase(insertBook.pending, (state, action) => {
        state.isLoading = true;
        state.error = null;
      }),
      builder.addCase(insertBook.fulfilled, (state, action) => {
        state.isLoading = false;
        state.books.push(action.payload);
      }),
      builder.addCase(insertBook.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      });
  },
});
export default bookSlice.reducer;

Here is Data on server data.json file:

{
  "books":[{
    "_id": "64027b8446d3263101d3a522",
    "name": "Medical Informatics and Bioimaging Using Artificial Intelligence",
    "photo": "https://media.springernature.com/w92/springer-static/cover/book/978-3-030-91103-4.jpg?as=webp",
    "des": "Aboul Ella Hassanien,   Roheet Bhatnagar,   Václav Snášel,   Mahmoud Yasin, Shams, Medical Informatics and Bioimaging Using Artificial Intelligence: Challenges, Issues, Innovations and Recent Developments. Studies in Computational Intelligence (SCI, volume 1005) 2022 ",
    "link": "https://link.springer.com/book/10.1007/978-3-030-91103-4"
    
},
{
    "_id": "64027bb846d3263101d3a526",
    "name": "Modeling, Control and Drug Development for COVID-19 Outbreak Prevention",
    "photo": "https://media.springernature.com/w92/springer-static/cover/book/978-3-030-72834-2.jpg?as=webp",
    "des": "Ahmad Taher Azar, Aboul Ella Hassanien Modeling, Control and Drug Development for COVID-19 Outbreak Prevention Studies in Systems, Decision and Control (SSDC, volume 366), 2022  ",
    "link": "https://link.springer.com/book/10.1007/978-3-030-72834-2"

},

How can I fix that error?

Take image from a website for mine in Javascript

i’m new to javascript and coding in general, i’ve already used Selenium on python before but i would like to know if it was possible for javascript to go onto a website, copy images and put them on my html file ?

i haven’t tried anything yet i wanna know if it’s possible

Typescript function that makes the object values as keys and the keys as values

I am trying to create a function that will invert the provided object.

For instance, I have this object

{
 a: "aee",
 b: "bee",
 c: "cee"
}

I want to make it

{
 aee: "a",
 bee: "b",
 cee: "c"
}

Using a function as follows:

mapSelf(myObject)

The logic in JavaScript is straight forward:

function mapSelf(object) {
  const result = {};
  for (const [key, value] of Object.entries(object)) {
    result[value] = key;
  }
  return result;
}
const test = mapSelf({
  a: 'aee',
  b: 'bee',
  c: 'cee',
})
console.log(test)
// {
//   "aee": "a",
//   "bee": "b",
//   "cee": "c"
// }

Doing this in typescript almost works!

function mapSelf<const T extends Record<string, string>>(
  object: T
): Record<T[keyof T], keyof T> {
  const result: any = {}
  for (const [key, value] of Object.entries(object)) {
    result[value] = key
  }
  return result
}

const test = mapSelf({
  a: 'aee',
  b: 'bee',
  c: 'cee',
})

However, I am losing the relation between the keys and their values in the final output.

When I try to hover over H

const H = test.aee

I get H inferred as

const H: "a" | "b" | "c"

I want H to be equal to its corresponding key, in this case, H should be inferred as “a”

Re-render on input entry in Redux

My problem is that when I enter anything into the input field, each symbol entered triggers a re-render, which I assume is what Redux does with useSelector(). I am trying to optimize my input field and redux store, so that the login value gets registered in redux only when I submit the final form.
My login process consists of several steps, which are divided into several components, which get rendered based on a value of a local state.

How can I make it so that when i enter email on the 1st page, it does not re-render on input.
I also noticed that due to the fact that my initialState is empty, I am getting the error “A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen.”. I saw solutions to this, but they say that you should explicitly define the state with the empty string to remove the error. I had set the initialState with empty strings to begin with, so i guess I made a mistake along the way.

Also noticed different behavior when I set the reducer differently.
In case of state.emailTelefon = action.payload.emailTelefon; — I am getting the error message mentioned above.

In case of:
state.emailTelefon = action.payload; — I am getting re-renders on every entry.

Truly getting confusing for my junior brain.

import { createSlice } from "@reduxjs/toolkit";

interface logDataProps {
  emailTelefon: string,
  logParola: string,
}

const initialState: logDataProps = {
  emailTelefon: "",
  logParola: "",
};

const logData = createSlice({
  name: "loginData",
  initialState: initialState,
  reducers: {
    setUserLogin: (state, action) => {
      state.emailTelefon = action.payload.emailTelefon;
    },
    setLoginParola: (state, action) => {
      state.logParola = action.payload.logParola;
    },
  },
});

export const { setUserLogin, setLoginParola } = logData.actions;

export default logData.reducer;

My Input component:

'use client'
import { ChangeEvent } from "react"
import { ReactEventHandler } from "react"


type InputFieldProps<T extends React.InputHTMLAttributes<HTMLInputElement> = {}>  = {
name: string;
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
id: string;
type?: string;
htmlFor: string;
value: string;
classNameInput?: string;
classNameLabel?: string
} & T;

const InputField: React.FC<InputFieldProps> = ({ name, id, type, htmlFor, value, onChange, classNameInput, classNameLabel }) => {
  return (
    <div className="relative">
      <input
        type={type}
        id={id}
        value={value}
        onChange={onChange}
        className={`${classNameInput} font-roboto tracking-body-large w-[360px] h-[56px] px-2 text-base text-gray-900 bg-transparent rounded-[4px] border-[1px] border-[#CAC4D0] focus:outline-none focus:border-[#6750A4] peer`}
        required
      />
      <label
        htmlFor={htmlFor}
        className={`${classNameLabel} ml-2 top-3.5 text-xl absolute  text-[#49454F] peer-focus:text-[#6750A4] duration-300 z-10 origin-[0] bg-white px-2 start-1 hover:cursor-text ${
          value ? "top-[-0.35rem] scale-50 -translate-y-2" : "scale-75 peer-placeholder-shown:scale-100 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:top-1/2 peer-focus:top-[-0.35rem] peer-focus:scale-50 peer-focus:-translate-y-2"
        }`}
      >
        {name}
      </label>
    </div>
  );
};
  
  export default InputField;
  
'use client'
import Link from "next/link";
import Button from "../buttons/Button";
import InputField from "../formControl/InputField";
import { useSelector, useDispatch } from "react-redux";
import { setUserLogin } from "@/app/redux/reducerSlices/logData";
import { RootState } from "@/app/redux/store";
import LoginHeaderComp from "./LoginHeaderWithIcon";

interface LoginWindowProps {
    onClickGoNext: () => void;
}

const FirstStepUsername: React.FC<LoginWindowProps> = ({onClickGoNext}) => {
    const  emailTelefon  = useSelector((state: RootState) => state.login.emailTelefon)
    const dispatch = useDispatch()
console.log(emailTelefon)

    return (
        <div className="flex flex-col pb-4 gap-4">
             <LoginHeaderComp />
        <h1 className="text-center font-roboto text-headline-small leading-headline-small pb-4">Loghează-te</h1>
            <InputField
                id={"loginInput"}
                name={"Email sau telefon"}
                type={"text"}
                htmlFor="loginInput"
                value={emailTelefon}
                onChange={(e) => dispatch(setUserLogin(e.target.value))}
            />
            <p className='font-roboto font-bold text-label-large leading-label-large tracking-label-large text-[#6750A4] hover:cursor-pointer'>Ai uitat emailul?
            </p>
            <p className='font-roboto text-body-medium leading-body-medium tracking-body-medium text-[#49454F] pt-2'>Vei accesa contul tău de transportator, operator sau ofițer vamal în funcție de accesul atașat la email.
            </p>
            <div className='flex flex-row justify-between items-center pt-6'>
                <Link href="/registration" className='font-roboto text-label-large leading-label-large tracking-label-large text-[#6750A4] hover:cursor-pointer ml-3'>
                    Creează un cont
                </Link>
                <Button name={"Intră"} onClick={onClickGoNext} className={"bg-[#6750A4] px-6 py-[10px] rounded-full text-white  leading-label-large tracking-label-large font-medium text-label-large hover:drop-shadow-[1px_1px_2px_rgba(163,159,164,255)]"} />
            </div>
        </div>
    )
}

export default FirstStepUsername;

Chainlink Functions Error in SendRequest to an API

I’m trying a basic integration of AI into Smart Contracts using Chainlink Functions and I got an error after sending the request, resulting in empty response, even though I’ve been charged for the API call.

Error during functions execution: Error: {“error”:true,”message”:”AbortError: The signal has been aborted”}

I’m making a text-to-image call. I thought it could be a timeout execution issue but I do not get how to address it anyway. Any help?

Thanks

This is the source script used to send the request:

const _prompt = args[0];

const postData = {
  model:"dall-e-3",
  prompt: _prompt,
  size:"1024x1024",
  n:1,
};

const openAIResponse = await Functions.makeHttpRequest({
  url: "https://api.openai.com/v1/images/generations",
  method: "POST",
  headers: {
    Authorization: `Bearer ${secrets.apiKey}`,
    "Content-Type": "application/json",
  },
  data: postData
});

if (openAIResponse.error) {
  throw new Error(JSON.stringify(openAIResponse));
}

const result = openAIResponse.data.data[0].url;

console.log(result);
return Functions.encodeString(result);

Creating a searchable directory on Hivebrite that accesses data stored in a google sheet

I am trying to create a directory on a Hivebrite page that users can utilize to search other users by name, state, zip code, etc. The data needing to be accessed for this is stored in a Google sheet. I have made the sheet “public” and set up the google sheet API, but it will not generate any results or show the data table when I try to preview the page. Any tips would be greatly appreciated 🙂

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Directory</title>
    <style>
        /* Your CSS styles here */
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="searchInput" placeholder="Search...">
        <ul id="directoryList"></ul>
        <div id="noResultsMessage">No results found.</div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#searchInput').on('input', searchDirectory);

            // Google Sheets API key
            var apiKey = 'AIzaSyBldgrtW7K5Hvm88n8szuXbgx4WlkPGy5U';

            // Google Sheets Spreadsheet ID
            var spreadsheetId = 'https://docs.google.com/spreadsheets/d/1O-3zjSGdQ9ZVG4KomiEYSIejmjkgi9slPkpODpFkJKQ/edit#gid=411563656';

            // Function to fetch and display data from the Google Sheets API
            function fetchDataFromSheet() {
                var apiUrl = 'https://sheets.googleapis.com/v4/spreadsheets/' + spreadsheetId + '/values/Sheet1?key=' + apiKey;

                fetch(apiUrl)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Failed to fetch data from Google Sheets. Status: ' + response.status);
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('Fetched data:', data);
                        displayData(data);
                    })
                    .catch(error => {
                        console.error('Error fetching data:', error);
                        // You can add further error handling or logging here
                    });
            }

            // Function to display data on the web page
            function displayData(data) {
                console.log('Displaying data...');

                var directoryList = $('#directoryList');
                var noResultsMessage = $('#noResultsMessage');
                directoryList.empty();
                noResultsMessage.hide();

                // Process the data and append it to the list
                var values = data.values || [];
                values.forEach(function (row) {
                    var listItem = $('<li class="directory-item"></li>');
                    listItem.html(
                        'ID: ' + (row[0] || '') +
                        ' | Last Name: ' + (row[1] || '') +
                        ' | First Name: ' + (row[2] || '') +
                        ' | Email: ' + (row[3] || '') +
                        ' | Website: ' + (row[4] || '') +
                        ' | Address: ' + (row[5] || '') +
                        ' | ZIP/Postal code: ' + (row[6] || '') +
                        ' | City: ' + (row[7] || '') +
                        ' | State/Region/Province: ' + (row[8] || '') +
                        ' | Country: ' + (row[9] || '') +
                        ' | Country code: ' + (row[10] || '')
                    );
                    directoryList.append(listItem);
                });

                // Trigger search after displaying data
                searchDirectory();
            }

            // Function to show all items when the page loads
            function showAllItems() {
                var directoryList = $('#directoryList');
                directoryList.find('.directory-item').show();
            }

            // Function to handle the initial data fetch
            fetchDataFromSheet();

            // Show all items when the page loads
            showAllItems();

            // Function to handle search functionality
            function searchDirectory() {
                console.log('Searching directory...');

                var filter = $('#searchInput').val().toUpperCase(); // Convert the search term to uppercase
                var directoryList = $('#directoryList');
                var noResultsMessage = $('#noResultsMessage');
                var resultsFound = false;

                directoryList.find('.directory-item').each(function () {
                    var txtValue = $(this).text().toUpperCase(); // Convert the text content to uppercase
                    if (filter === '' || txtValue.indexOf(filter) > -1) {
                        $(this).show();
                        resultsFound = true;
                    } else {
                        $(this).hide();
                    }
                });

                if (!resultsFound) {
                    noResultsMessage.show();
                } else {
                    noResultsMessage.hide();
                }
            }
        });
    </script>
</body>
</html>

Show or hid div on IOS and Mac

Im trying to show an image for only mac and ios for imessage fuction on the website im working on. The code i have is with help of other sources on stack. Can anyone assist to why its not working. I do have the div to display none at the start.

<script type="text/javascript">
  // Function to check if the user is using iOS or macOS
  function isIOSorMac() {
    return /iPad|iPhone|iPod/.test(navigator.userAgent) || navigator.platform === 'MacIntel' || navigator.platform === 'MacPPC';
  }

  // Function to show or hide the div based on the device
  function showOrHideDiv() {
    var iosMacDiv = document.getElementById('ios-message');

    if (isIOSorMac()) {
      iosMacDiv.style.display = 'block';
    } else {
      iosMacDiv.style.display = 'none';
    }
  }
</script>


<!-- END Show IOS Button for Chat END-->

I have tried adding a fuction to start the fuction at page load, but then get hung up on iosMacDiv.style.display = 'none';

How do I stop visual studio inserting a space into JavaScript code on build/rebuild?

I am using Visual Studio 2019 Enterprise. When I build/rebuild my solution ASP.net 4 MVC my JavaScript files are removed as they are regenerated by my TypeScript files.

However the new JavaScript files have a single trailing space after { or } or ;

I have tried to remove the Autoformatting for JS/TS in tools => options but still those single trailing space are added.

Any idea?

So Far I have tried re-installing VS 2019 and change the tools option settings for JS/TS

Bootstrap selectpicker option size inside a Modal

How do I adjust the width of a selectpicker’s option within a Modal?
The width of the select is normally adjusted to the width of the modal, but when I open the selectpicker, the data in the option adjusts to the total width of the screen. Here’s an example of how I’m using the modal:

<div class="modal fade" id="mymodal" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog"
aria-labelledby="mymodal" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content" style="border-radius: 0">
        <div class="modal-header">
            <h6 class="modal-title"> My Modal</h6>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                    aria-hidden="true">&times;</span></button>
        </div>
        <form role="form" id="form1" name="form1" method="post" action="action.do">
            <div class="modal-body" style="overflow: visible;">

                <div class="form-group">
                    <select class="selectpicker form-control" data-container="modal-body" data-live-search="true"
                        required data-style="btn-light btn-outline-secondary btn-sm btn-custom">
                        <option value=""><span>Select a value</span></option>
                        <option value="1"><span>Value 1</span></option>
                        <option value="2"><span>Value 2</span></option>
                        <option value="3"><span>Value 3</span></option>
                        <option value="4"><span>Value 4</span></option>
                        <option value="5"><span>Value 5</span></option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm btn-outline-secondary" data-dismiss="modal">Exit</button>
            </div>
        </form>
    </div>
</div>

enter image description here

enter image description here

Accessing the value of a field inside a class method

I apologize in advance for my clumsy English. I’ve been writing in React for a while now, but this is my first encounter with this issue. You can see the service class, which includes the #basketUrl (just string “/basket”) field with a request link and two implementations of the same method, createBasket.

import $axios from "../axios";
import { ServerPaths } from "../enum/ServerPaths";

class BasketService {
  #basketUrl = ServerPaths.BASKETS;
  #basketProductUrl = ServerPaths.BASKET_PRODUCTS;

  async createBasket (userId) {
    await $axios.post(`${this.#basketUrl}`, { userId });
  }

  createBasket = async (userId) => {
    await $axios.post(`${this.#basketUrl}`, { userId });
  }
}

In the first case, the code doesn’t recognize ‘this’; it interprets it as undefined, hence ‘this.url – cannot read properties of undefined,’ as there’s no variable ‘url’. In the second case – all ok.

At the same time, in the online compiler, the same code ran smoothly and provided me with the value of the field.

Please explain Why only the arrow function works in my React code.

Everything works with an arrow function, but I want to get to the bottom of this question.