One of my Navabr links is not working reactjs/Three.js?

I am following a youtube video (three.js ) to make web portfolio. Now I made some changes to the components according to the links I want. One of the links, i.e link to the project, is not working but the other two links about and contact are working and I can jump to those components. I tried debugging the code but I don’t know where the id’s are coming from if someone can review my code it would be great.

Navbar.js

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { styles } from '../styles';
import { navLinks } from "../constants";
import { logo, menu, close } from '../assets';

const Navbar = () => {
  const [active, setActive] = useState("");
  const [toggle, setToggle]=useState(false);

  return (
    <nav className={`${styles.paddingX} w-full flex items-center py-5 fixed top-0 z-20 bg-primary`}>
      <div className='w-full flex justify-between items-center max-w-7xl mx-auto'>
        <Link to ="/" className='flex items-center gap-2' onClick
        ={()=>{
          setActive("");window.scrollTo(0,0);
        }}>   <img src={logo} alt='logo' className='w-9 h-9 object-contain' />
          <p className='text-white text-[18px] font-bold cursor-pointer'>
            ar &nbsp; <span className='sm:block hidden'></span></p>
         </Link>
         <ul className='list-none hidden sm:flex flex-row gap-10'>
          {navLinks.map((link)=>(
            <li key={link.id} className={`${active === link.title ? "text-white":"text-secondary"}
            hover:text-white text-[18px] font-medium cursor-pointer
            `}
            onClick={()=> setActive(link.title)}
              
            >
              <a href={`#${link.id}`}>{link.title}</a>
              {/* <Link to={`#${link.id}`}>{link.title}</Link> */}
              
            </li>
          ))}

         </ul>
         <div className='sm:hidden flex flex-1 justify-end items-center'>
          <img src={toggle?close:menu} alt="menu" className='w-[28px] h-[28px] object-contain cursor-pointer'
          onClick={()=>setToggle(!toggle)}/>
          <div className={`${!toggle ? 'hidden' :'flex'} p-6 black-gradient absolute top-20 right-0 mx-4 my-2 min-w-[140px] z-10 rounded-xl` }>
          <ul className='list-none flex justify-end items-start flex-col gap-4'>
          {navLinks.map((link)=>(
            <li key={link.id} className={`${active === link.title ? "text-white":"text-secondary"}
            font-poppins font-medium cursor-pointer text-[16px]
            `}
            onClick={()=>{ setToggle(!toggle) ; setActive(link.title)}}
              
            >
              <a href={`#${link.id}`}>{link.title}</a>
              {/* <Link to={`#${link.id}`}>{link.title}</Link> */}
            </li>
          ))}

         </ul>
          </div>
         </div>
         
      </div>

    </nav>
  )
}

export default Navbar

In constants /index.js

export const navLinks = [
  {
    id: "about",
    title: "About",
  },
  {
    id: "work",
    title: "Project",
  },
  {
    id: "contact",
    title: "Contact",
  },
];

App.js

import { BrowserRouter } from "react-router-dom";
import {
  About,
  Contact,
  Experience,
  StarsCanvas,
  Works,
  Tech,
  Navbar,
  Hero,
  Feedbacks
} from "./components";

const App = () => {
  return (
    <BrowserRouter>
      <div className="relative z-0 bg-primary" >
        <div className="bg-hero-pattern bg-cover bg-no-repeat bg-center">
          <Navbar />
          <Hero />
        </div>
        <About />
        <Experience />
        <Tech />
        <Works />
        <Feedbacks />
        <div className="relative z-0">
          <Contact />
          <StarsCanvas />
        </div>
      </div>
    </BrowserRouter>
  )
}

export default App

Here is the file structure
enter image description here
three links

dayjs order of parsing

I am currently using dayjs along with the CustomParseFormat plugin. In my application, I utilize German date formats, specifically ‘DD.MM.YYYY’. However, I want to allow users to input partial dates without periods, such as ‘MYYYY’.

My expectation was that when I use the code dayjs(‘52023’, ‘MYYYY’), it would correctly parse the date with the month set to 5 and the year set to 2023. Unfortunately, it returns an invalid date. The issue appears to be that dayjs parses date strings from left to right, resulting in the month being set to 52 and the year to 023, which is not a valid date.

I understand that one workaround would involve reversing the format to ‘YYYYM’ and inputting the date as 20235, which would work, but it’s not the desired solution.

Thank you for your help.

Record audio that plays back on all major browsers using javascript MediaRecorder

Goal

I am trying to record audio in the browser using MediaRecorder. This audio gets uploaded to a server and should then be playable for other users.

Problem

I can not seem to get a recording in a file type that works across all browsers (Safari being the main problem).
For example, audio recorded in Safari (audio/mp4 with AAC encoding) can be played in Chrome/Firefox. BUT audio recorded in Chrome/Firefox can not be played in Safari. No matter the mimetype I choose.

Question

Reading through other SO questions (e.g. mediaRecorder : what mime type to use to make it run on Safari, Chrome and Firefox?) did unfortunately not give me more information on this.

Is there a way to record using the MediaRecorder api in a format that can be played on Chrome/Firefox/Safari? The recorded format does not need to be the same on all browsers, but it should be playable on all browsers.

If this is not possible. What is a good format to convert to using FFMPEG? The mp4 aac format gave me good results, so this looks appealing, but as I will be encoding to aac, I think the license for that codec would require me to pay a fee. Is there any other free codec usable?

Axios responding two times

function Homepage() {
    const url = `https://cloud.iexapis.com/stable/stock/aapl/quote?token=token`;
    useEffect(()=>{
        axios.get(url)
        .then(res => {
            console.log(res.data);
        })
        .catch(err => {
            console.log(err);
        })
    }, [])
}

I’m trying to fetch data from the api, but why this code gives me two identical responses.enter image description here

How should I fix it, so I can get only one response from api?

error to compress multiples image file and donwload

i’m rookie to this new world of programming and need some help with express-zip and node.js

i’m able to make a single download of an image from instagram, but, when the user pastes a link that contains 2 o 3 or more images, the server stops.

So, i tried to implement express-zip to put all the media inside of it and download.

what happens is that when the download starts, he never finish and the size of the file is like, 66bytes

here my code

const express = require("express");
const request = require("request");
const bodyParser = require("body-parser");
const instaAPI = require("igdown-scrapper");
const { JSDOM } = require("jsdom");
const app = express();
let data;
const port = 3000;
let arrayDocs = [];
let zip = require("express-zip");

app.use(bodyParser.urlencoded({ extended: false }));
app.set("view engine", "ejs");

app.get("/", (req, res) => {
  res.render("index");
});

app.post("/download", async (req, res) => {
  const url = req.body.url;
  console.log(url);
  if (!url || !url.startsWith("https://www.instagram.com/")) {
    res.render("index", { error: "Invalid URL" });
    return;
  }

  instaAPI(url).then((response) => {
    data = response;
    console.log(data.length);
    if (data.length > 1) {
      let count = data.length;
      // console.log(data[0].url[0]);

      if (data[0].url[0].ext == "mp4") {
        for (x = 0; x < count; x++) {
        //   multipleDownloads(x, data[x].url[0].url, "mp4");

          arrayDocs.push({ path: `${data[x].url[0].url}`, name: Date.now() + `${x}.` + "mp4" })

          if (x === data.length - 1) {
            console.log("Zip file send")
           
            res.zip(arrayDocs);
        } 
        else{
            continue;
        }
        }
      } else {
        for (x = 0; x < count; x++) {
        //   multipleDownloads(x, data[x].url[0].url, "jpg");

          arrayDocs.push({ path: `${data[x].url[0].url}.jpg`, name: Date.now() + `${x}.` + "jpg" })

          if (x === data.length - 1) {
            console.log("Zip file send")
            console.log(arrayDocs);
            res.zip(arrayDocs);
        } 
        else{
            continue;
        }
        }
      }
    } else if (data.url[0].ext == "mp4") {
      downloadFile(res, data.url[0].url, "mp4");
    } else {
      downloadFile(res, data.url[0].url, "jpg");
    }
  });
});

async function downloadFile(res, url, ext) {
  request(url, { encoding: null }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      res.status(400).send("Error downloading image");
      return;
    }

    const fileName = Date.now() + "." + ext;
    res.setHeader("Content-Type", "application/octet-stream");
    res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
    res.send(body);
  });
}

app.listen(port, () => {
  console.log("App is listening on port 3000");
});

make the express-zip integration work with instagram medias

How to generate environmental sounds programmatically?

I want to make sounds for my game. I can record them myself, but the problem is that these sounds will always be the same and this is a very large amount of work. And I would like sounds to be generated depending on different game conditions.

What should these sounds be: click-clack, knock-knock, whoosh-whoosh, bang-bang, top-top.
This is not music, but very short environmental sound effects that could create a lively game atmosphere.
For example, the sound of walking. This sound lasts less than 1 second and I want it to be different.

I see it this way. To begin with, I will record 10 sound effects on my own, so that I have something to generate them from. And then my program must somehow modify these sounds to give the impression that the sounds are constantly different.

Is it possible to do this? If you know other ways, please let me know how it can be done.
My game is written with JavaScript, and PHP on backend.

vitest vi.spyOn does not work on side effects?

I would like to use `vi.spyOn` to monitor the call to an sideEffect function
in a module to make sure is being called by another function in a module.

I did this on jest without problems but it does not seem to work on vitest.

Here is a simplified example

aModule.ts

export function a() {
  return sideEffect();
}

export function sideEffect() {
  return 'a';
}

Here is the test file:

import { vi, expect, test } from 'vitest';
import * as aModule from '../src/aModule';

test('expect "sideEffect" to be called at least once', async () => {
  const sideEffectSpy = vi.spyOn(aModule, 'sideEffect').mockReturnValue('b');
  const aSpy = vi.spyOn(aModule, 'a');

  const res = aModule.a(); // This function calls sideEffect internally.
  expect(res).toBe('b'); // This fails - it returns 'a' so the spyOn is not workng
  expect(sideEffectSpy).toHaveBeenCalled(); // This fails as well :( 
});

I did try a few variations on this, but could not make it work. Any ideas?

Thx.

How to compare items in an object nested in an array with an object which has an array of items in it?

I’m trying to find recipes which match Authors of my searchArray. The searchArray is an array of authors in an object. The recipes I’m matching this searchArray with, are objects in an array.

I’ve changed the array to a string, thinking that this would make matching more easy. I also changed the searchArray and the Authors in the recipes toLowerCase() and then tried to find recipes matching at least 1 of the authors in the searchArray.

If someone searches with only the first name, then any recipe with an author with that first name is fine. However, if someone searches with first and last name, then the author in the recipe should be an exact match, that’s why the first if statement has (” “), indicating a space between first and last name.

Is my way of thinking wrong or am I writing very bad functions (or all of these errors in my brain):

const searchRecipeWithAuthor = (searchArray) => {
  const { authors } = searchArray;
  const searchAuthor = authors.toString().toLowerCase();
    // console.log(searchAuthor); // tested and works 

  const matchingRecipes = cakeRecipes.filter(({ Author}) => {
    // console.log(Author)); // gives all Authors as string
    const recipeAuthor = Author.toLowerCase();
    // console.log(recipeAuthor); // tested and works
    
    if (searchAuthor.includes(" ")) {
       // console.log(searchAuthor); // tested and works
      if (searchAuthor === recipeAuthor) {
        // can't test from this part, dus to TypeError referencing const recipeAuthor = //Author.toLowerCase();  Cannot read properties of null (reading 'toLowerCase')
        return true;
      } else {
        if (recipeAuthor.includes(searchAuthor)) {
          return true;
        }
      }
    }
  });
  return matchingRecipes.map((recipe) => recipe[0]); 
};  

console.log(searchRecipeWithAuthor(searchParams)); 

I’ve shared the code with still some console.log statements in it, to check which parts weren’t working. Halfway I couldn’t check anymore. I get the following Error message:

TypeError: Cannot read properties of null (reading 'toLowerCase')
    at /home/runner/JS-module-7-assignment-cake-search/index.js:59:33
    at Array.filter (<anonymous>)
    at searchRecipeWithAuthor (/home/runner/JS-module-7-assignment-cake-search/index.js:57:39)
    at Object.<anonymous> (/home/runner/JS-module-7-assignment-cake-search/index.js:77:13)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)

The line this Error message is referring to, is

const recipeAuthor = Author.toLowerCase();
    // console.log(recipeAuthor); // works

When I tried console.log, it did give me all the authors of all the recipes in lowercase.

Update location of google maps marker without refreshing the page

am trying to update the location of a marker on google maps using javascript. the new new coordinates i want to update to. are returned from the server by an ajax call( Note : this ajax call happens only when the user clicks on the object )

this is my ajax call code snippet and my function to update the location of the marker, thanks in advance

$.ajax({
  type: "POST",
  url: "data",
  data: {"v":dvx_datarc},
  success: function(satelite_data){
     var sys_res = JSON.parse(satelite_data);
     var NewLat = sys_res.data.new_lat;
     var NewLog = sys_res.data.new_log;
                    
     updateMarkerLocation(i,NewLat,NewLog);
   }
  });
function updateMarkerLocation(markerId, lat, lng) {
        // Find the specific marker based on the markerId or identifier
            var specificMarker = findMarkerById(markerId);

            // Check if the marker is found
            if (specificMarker) {
                var newPosition = new google.maps.LatLng(lat, lng);
                
                // Update marker position
                specificMarker.setPosition(newPosition);
                
                // Center the map on the new marker position
                map.setCenter(newPosition);
                map.panTo(newPosition);
            }
        }
function findMarkerById(markerId) {
  // Loop through the markers array and find the specific marker
  for (var i = 0; i < markersOnMap.length; i++) {
    if (markersOnMap[i].id === markerId) { // Adjust the condition based on your marker's properties
      return markersOnMap[i];
    }
  }
  
  // Marker not found
  return null;
}

How can I use a bookmarklet to get an innerText from an external domain iframe? (x-origin errors)

I’m trying to use a bookmarlet to get a value from an iframe, which is loaded from another domain. I’m getting x-origin errors, but I don’t need to communicate “between” the frames, I just need to read data from the iframe, like I would from the parent.

I do not have access to modify either the parent or child frame. I cannot load the child iframe alone either.

I recreated a super simplified version of the structure I’m working with.

Parent page
url1.com/parent.html

<body>
  <h1>Parent Title</h1>
  <iframe src="url2.com/child.html" id="xoFrame"></iframe>
</body>

Child iframe
url2.com/child.html

<body>
  <h1>Child Iframe Title</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus congue est vitae mauris pulvinar hendrerit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p>
  <a class="button" href="#">Child Frame Button</a>
  <footer>&copy; Footer Text 2048</footer>
</body>

For the purpose of this test, I’m trying to get the innerText of a.button inside the iframe. I created four different bookmarlets to illustrate my point.


Bookmarklet 1

console.log('TEST 1. TRYING TO ACCESS PARENT > H1:');
console.log(document.querySelector('h1').innerText);

Result 1

TEST 1. TRYING TO ACCESS PARENT > H1:
Parent Title

Bookmarklet 2

console.log('TEST 2. TRYING TO ACCESS CHILD IFRAME > A.BUTTON DIRECTLY');
console.log(document.querySelector('a.button').innerText);

Result 2

TEST 2. TRYING TO ACCESS CHILD IFRAME > A.BUTTON DIRECTLY
Uncaught TypeError: Cannot read properties of null (reading 'innerText')
    at <anonymous>:1:132
    at <anonymous>:1:145

Bookmarklet 3

console.log('TEST 3. TRYING TO ACCESS IFRAME > CONTENTWINDOW');
console.log(document.getElementById('xoFrame').contentWindow);

Result 3

TEST 3. TRYING TO ACCESS IFRAME > CONTENTWINDOW
global {window: global, self: global, location: {…}, closed: false, frames: global, …}

Bookmarklet 4

console.log('TEST 4. TRYING TO ACCESS IFRAME > CONTENTWINDOW > DOCUMENT');
console.log(document.getElementById('xoFrame').contentWindow.document);

Result 4

TEST 4. TRYING TO ACCESS IFRAME > CONTENTWINDOW > DOCUMENT
Uncaught DOMException: Blocked a frame with origin "url1.com" from accessing a cross-origin frame.
    at <anonymous>:1:147
    at <anonymous>:1:159

All I need is a solution that would return Child Frame Button in this scenario.

Implementing Hover Effects, Adding Buttons, and Improving Design for an Expanding Content Card in WordPress

I am currently working on an Expanding Content Card for a WordPress website using HTML, CSS, and JavaScript. I have developed it without relying on any CSS frameworks. I have a few questions regarding its functionality and design:

  1. How can I implement a feature where the description text (.wdg-description) appears just below the title when the user hovers over it?
  2. I would like to add a button that is only visible when the user hovers over the content card. How can I achieve this?
  3. I’ve noticed that the current design doesn’t align perfectly with the mocks. Are there any suggestions or best practices to improve the design?

Thank you in advance for your assistance!

1st screen without mouseover

2nd Screen on Mouseover

```

```

Please see the codepen I have tried to meet the perfection. Are there any suggestions or best practices to improve the design?

How to make an auto infinite repeat slideshow animation

i want to make a slide show animation with 5 infinite rotating containers from right to left with a 5s delay and each container includes text and image.

<section class="slide__container">
    <div class="slides row">
        <div class="slide">
            <div class="text">
                <div class="pg">
                    <p>Do You Want Comfort ?</p>
                </div>
                <div class="btn__bg">
                    <button class="btn" >DISCOVER  &rarr;</button>
                </div>
            </div>
            <div class="img__bg">
                <img class="img" src="./img/Audi_Q3-removebg-preview.png" alt="Audi Q3">
            </div>
        </div>
</section>

How to rotate text around its center in jsPDF

When applying an angle to a text in jsPDF, it seems that the text is rotated around its left point of its baseline, while my goal is to rotate the text around its center.

This is the code that I am applying:

// Create the jsPDF instance
doc = new jsPDF({
    orientation: 'p',
    unit: 'mm',
    format: [250, 180]
});

// Rotate the text
doc.text("Text to rotate", 80, 80, {
    angle: 45
});

// Save the document
doc.save();

In the documentation, there is no property in the text() method that allows to set the origin of the rotation as the center of the text field.

Is there a way to go around this limitation ?

How to insert an element into a HTML input field?

I have to develop a script (extension content script) that will be inject in any page that contains a form.

In that page, the script has to insert into some input field, aligned to right, a clickable element (button for example).

The html page:

<div>
    <input type="text" id="input-field">
</div>

The script:

var button = document.createElement("button");
button.textContent = "?";

var inpuntField = document.querySelector("#input-field");

// Here I have to insert the button into the input field

The result must be like this:

-------------------
|               ? |
-------------------

I found a lot of solutions for this, but all of them need to edit the style attribute of the input element or the input’s parent,
and I don’t want to edit the original page, to prevent any problem with the page’s view.

Does anyone know how to do this or can suggest a solution? Grateful.

Could onmousedown() event act on mobile devices the same way it does on PCs? [duplicate]

I’m trying to suggest on-the-fly translation while a user reads a text and clicks/tap on highlighted words.

I use <a> tags to highlight words:

a {text-decoration: none; background-color: #dcf6c1; padding: 0px 5px; border-radius: 5px;}
a:hover {text-decoration: none; background-color: #167432; color: #dcf6c1;}
a:active {text-decoration: none; background-color: #167432; color: #dcf6c1;}

And the result is:

highlighted text

The following is the HTML:
Bisogna che, <a onmousedown="alert('tomorrow')">per domani</a>, tu

This worked well on PCs, but with a long tap on mobile devices I got this ugly highlighted selection:

ugly highlighted selection

So I added the following code in the body{}, to prevent selections:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

Everything works well on PC:

  1. when users click on highlighted text, text background-color and color change the way it should be;
  2. the alert message prompts fine;
  3. when the user click on “OK”, the alert closes and the highlighted text get back to the previous style.

But on mobile devices things go a different way:

  1. when users shortly tap on highlighted text, the background-color and color text do not change;
  2. changes apply only with a long tap (and if the tap is too long, alert message doesn’t prompt);
  3. when the user click on “OK”, the alert closes and the highlighted text do not get back to the previous style.

I surfed the net a lot, obviously mobile devices act different from PCs and what I understood is that probably the onmousedown() event is performed before style changes could apply (a:hover, a:active), but I couldn’t find a workaround.

I tried using a:focus pseudo-class, but didn’t work.
Using Javascript (instead of CSS code) for disabling selections also didn’t work:
<script type="text/javascript" src="js/disable.js"></script>

disable.js file:

window.onload = function() {
document.onselectstart = function() {return false;} // ie
document.onmousedown = function() {return false;} // mozilla

I’d like that on mobile devices, things go the same way that go on PC.

Hope somebody could help.