Javascript: get the closest Node, not the closest Element

I want to query all the <div> from the div element of class tab-content, which is a sibling of the div element with class tabs, which is a parent of the current <li> element.

Suppose tab is one of the tabs and the current node. This code:

const tabContent = tab.closest('.container').querySelectorall('.tab-content > div');

is returning an error querySelectorall is not a function, because closest() is returning an Element, not a Node.

So how to get that freaking closest node instead of the element (in pure JavaScript, no JQuery) ?

Here’s the HTML:

<div class="container">
    <div class="tabs">
        <ul>
            <li>Tab 1</li>
            <li>Tab 2</li>
            <li>Tab 3</li>
            <li>Tab 4</li>
        </ul>
    </div>
    <div class="tab-content">
        <div id="id1">Content for Tab 1</div>
        <div id="id2">Content for Tab 2</div>
        <div id="id3">Content for Tab 3</div>
        <div id="id4">Content for Tab 4</div>
    </div>
</div>

UseEffect not triggering in child component

I have a ‘user’ object that is loaded in the parent component, and passed to this child ‘feed’ component.
However, I’m using a useEffect hook to try and load more data using that user object but the useEffect block is never triggered. testing it here with the console.log which never shows up. But even when the normal async function I use to load the ‘posts’ and ‘setLoading’ is in the block nothing happens.

it seems like the useEffect is always ignored and the “loading” and “no posts” div is always what shows up.

Child:

const Feed = ({user}: FeedProps) => {
    const [posts, setPosts] = useState<
        { text: string | null; id: string; userId: string; file: string | null; timeStamp: Date }[] | null
    >(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        console.log("fetching posts");
    }, [user]);

    console.log("posts: ", posts);

    if (loading) {
        return <div>Loading...</div>;
    }

    if (!posts || posts.length === 0) {
        return <div>No posts available.</div>; 
    }

    return (
        <div className=" border-2 border-solid border-violet-700 w-5/6 h-full">
            {posts?.map((post) => (
                <PostCard key={post.id} post={post}/>
            ))}
        </div>
    )
}

export default Feed;

Parent:

const ProfilePage = () => {

    const user = useCurrentUser();  

    return (
          {user && <Feed user={user}/>}
    )
}
export default ProfilePage;

Helper functions:

import { useSession } from "next-auth/react";

export const useCurrentUser = () => {

    const { data: session } = useSession();

    return session?.user;
};

import { db } from "@/lib/db";

export const getUserPosts = async (userId: string) => {
    try {
        const posts = await db.post.findMany({ where: { userId } });
        return posts;
    } catch (error) {
        console.error("Error fetching posts:", error);
        return null;
    }
}

compilation of packages using @vercel/ncc

would like to know if anyone has used @vercel/ncc for compiling packages in a project or framework?

I have recently used this library in our project for compiling packages into single compiled file but getting various issues and compilation errors like:

  • Typescript related error: “files” list in config file tsconfig.json is empty
  • JSX compilation error: you may need an additional loaders to handle the result of these loaders

project structure:

packages/
   packageA/
      node_modules/
      package.json
      tsconfig.json
      src/
         index.ts
         client/
           testComponent.tsx
         server/
           index.js
      dist/

Additionally, after successful compilation of packages how to update the references of each packages from original source to compiled path?

for example –

index.js before:

import ABC from "@package/xyz"

index.js after compilation, reference updated:

import ABC from "./compiled/xyz"

Intermittent Section Reload/Glitch on Scroll in Next.js App

I’m encountering an issue with my Next.js app where page sections initially load correctly, but after scrolling down and then scrolling back up, they glitch. The sections seem to reload with a brief white space, then appear in bits and parts before displaying fully again, even though the DOM is already loaded. I haven’t implemented any dynamic reloading logic, and this happens in a way that disrupts smooth scrolling.

Here’s a reference to two sites experiencing similar behaviour:

  1. https://thegrandregent.com/
  2. https://www.15cacb.com/

Any guidance on potential causes or solutions would be appreciated!

How to Implement SWR (Stale-While-Revalidate) Functionality with the Options API in Vue 2?

I am working on a project using Vue 2 and would like to implement the SWR (Stale-While-Revalidate) functionality for data fetching. However, I have found that popular libraries like SWRV and TanStack (vue-query) can only be used within the setup function. My colleagues primarily use the Options API in Vue 2 for development. Since they are mostly backend developers and are not familiar with the setup syntax, I need to find a way to implement SWR functionality within the Options API.

I have attempted to solve it by writing a mixin to manage all requests. However, I find this approach to be inelegant. Specifically, every time I make a request, I end up with a Vue instance, which complicates the management of data and state.

Is there a way to integrate SWRV or TanStack (vue-query) with the Options API in Vue 2? If not, are there any alternative libraries or approaches that can achieve similar functionality within the Options API?

Thank you for your help!

How Can I Clear Cookies for my Web Application Using Javascript?

I have an ASP.NET web application built with .NET Framework 4.6.2. This application logs users into their accounts for a separate engineering application to display data in a web interface. When users click a logout button, they are redirected to a logout page. Behind the scenes, their session for the engineering application is cleared. However, I also need to clear the cookies for the web application when the logout page loads.

The first thing I did was determine what path the cookies for my website were being stored. They were being stored in the / path.

Next, I added the following javascript to my logout.aspx page:

<script type="text/javascript">
    function deleteCookie(name) {
        document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    }

    function clearAllCookies() {
        const cookies = document.cookie.split(';');
        cookies.forEach(cookie => {
            const cookieName = cookie.split('=')[0].trim();
            deleteCookie(cookieName);
            deleteCookie(cookieName, "/");
        });
    }
    //Clear cookies on logout
    window.onload = function () {
        clearAllCookies();
    }
</script>

I pushed this updated code to my test server, and when I clicked my logout button, I navigated to chrome://settings/content/all and saw that the cookie for my website was still there. Is there a more effective way that I can clear the cookies for my web application?

ClerkClient.emailAddresses.createEmailAddress does not send verification email

So im trying to build a custom settings page for my SaaS which uses Clerk. I am able to create a new email for the user, but i am setting “verified” to false, since i want the user to receive an email to verify, but clerk does not send any email?

const emailAddress = await ClerkClient.emailAddresses.createEmailAddress({
    userId: user.id,
    emailAddress: email,
    primary: false,
    verified: false,
});

If i use the regular built in clerk component and try adding an email, it send a verification email.

Does anyone have the same issue?

I have tried scanning the docs but there is very little about this, and the little info there is does not seem to be correct.

How to convert a string into camel case with JavaScript regex without apostrophe and white space?

I am struggling on how to convert a string into camel case without apostrophe and white space. Here is my code so far:

function toCamelCase(input) {
  return input
    .toLowerCase()
    .replace(/['W]+(.)?/g, (_, char) => (char ? char.toUpperCase() : ""))
    .replace(/^./, (char) => char.toLowerCase());
}

const result2 = toCamelCase("HEy, world");
console.log(result2); // "heyWorld"

const result3 = toCamelCase("Yes, that's my student");
console.log(result3); // "yesThatsMyStudent"

“”HEy, world”” works. The problem is that it is failing on “Yes, that’s my student”. I got “yesThatSMyStudent” instead of “yesThatsMyStudent”. I have no idea why the “s” in “that’s” is not lowercase. Can someone please explain why this is happening and point me in the right direction? Thank you.

Condition not returning errors (Express.js)

When I call a GET request in Postman with the url “localhost:3000/api/users/id/” without the number of the ID, I’d like to have a return like this one when I call a GET request with the query empty:

{
    "errors": [
        {
            "type": "field",
            "msg": "Must not be empty",
            "path": "filter",
            "location": "body"
        }
}

but insteaded this is the return I have:

<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /api/users/id/</pre>
</body>

this the code:

app.get("/api/users/id/:id", findUserIndex, checkSchema(getUserValidationIdSchema), (req, res) => {

    const result = validationResult(req);
    const {userIndex} = req;

    if (!result.isEmpty()) return res.status(400).send({errors: result.array()});

    if (result.isEmpty()) return res.send(users[userIndex]);

})

this is the function finderUserIndex:

const findUserIndex = (req, res, next) => {

    const {params: {id}} = req;
    const parsedId = parseInt(id);

    if (isNaN(parsedId)) return res.sendStatus(400);

    const userIndex = users.findIndex((user) => user.id === parsedId);

    if (userIndex === -1) return res.sendStatus(404);

    req.userIndex = userIndex;
    req.parsedId = parsedId;

    next();

}

and this is the schema get getUserValidationIdSchema:

export const getUserValidationIdSchema = {
    id: {
        notEmpty: {errorMessage: "Must not be empty"},
    }
}

React: How to run one app inside shadow dom of main app?

For context, I am using vite, but I believe the issue would be the same with next.js.

With React, I have my “main app” and “module app” for example chat client. I don’t want to use iframe of “module app” inside “main app” or make static build of “modeule app” and insert it as /public static lib and also I don’t want to merge their components, libs, public files to single app.
Is there solution to use second app as a component with own dependencies, public, src, tsconfig and so on?
May be like using

    <div id="app"></div>
    <div id="module_app"></div>

inside index.html or

    <div id=“module_app”></div>

somewhere deeper in react app?
And of course shadow root is needed here to escape apps global styles.

The scenario of a question is I have many standalone apps as a web chat, picture editor, accounting documents creator, server monitoring and more, each of them has own git repo. Each of them perfecly works as standalone app and now I need to use some of them as part of main app.

NodeJS how to run one app inside shadow dom of main app?

In my case I’m using vite and react but it doesn’t realy matters could be nextjs. I have my “main app” and “module app” for example chat client. I don’t want to use iframe of “module app” inside “main app” or make static build of “modeule app” and insert it as /public static lib and also I don’t want to merge their components, libs, public files to single app.
Is there solution to use second app as a componet with own dependencies, public, src, tsconfig and so on?
May be like using

<div id="app"></div>
<div id="module_app"></div>

inside index.html or

<div id=“module_app”></div>

somwhere deeper in react app?
And ofcourse shadow root is needed here to escape apps global styles.

The scenario of a question is I have many standalone apps as a web chat, picture editor, accounting documents creator, server monitoring and more, each of them has own git repo. Each of them perfecly works as standalone app and now I need to use some of them as part of main app.

Why is my game’s lag get more worse when I play it further?

This is a prototype game about a goose who has to keep the temperature right or else the world ends. I’m trying to add in more mechanics in but I really can’t move on because the lag gets worse the more you play. Is there anything I can reduce or simplify?

let gabHeatColor = 0;
let gabThermoStat = 30;

var gooseHonk;
let laserHue = 0;

//denaplesk2 game timer
let timerValue = 30;
let startButton;

let timerBar = 0; //will appear @ top screen

function preload() {
  soundFormats('wav');
  gooseHonk = loadSound('spacejoe_bird-honk-2.wav');
}

function mousePressed() { //plays goose honk
  gooseHonk.play();
}

function setup() {
  createCanvas(windowWidth, windowHeight);
  // textAlign(CENTER);
  setInterval(timeIt, 1000);
}

function timeIt() {
  if (timerValue > 0) {
    timerValue--;
  }
}

function draw() {
  // frameRate(20);
  background(140, 140, 72);
  strokeWeight(0);
  
  fill(107, 94, 43); //floor background
  rect(0, windowHeight/1.3, windowWidth, windowHeight);
  
  fill(140, 213, 237); //window
  rect(windowWidth/3, windowHeight/7, 200, 450);
  
  //timer > winstate or gameover
  fill(0);
  if (timerValue <= 60) {
    text(timerValue + " SECONDS", width / 3, height / 10);
  } else {
    text(timerValue + " SECONDS, You WIN!", width / 3, height / 10);
    frameRate(0);
  } 
  
  if (gabThermoStat > 100) {
    gabThermoStat = 999;
    text("oops world heated", 50, 50);
    text("Oh no SECONDS, You LOSE!", width / 3, height / 10);
  } if (gabThermoStat <= 0) {
    gabThermoStat = -99;
    textSize(windowWidth/20);
    text("oops world frozen", 50, 50);
    text("NO SECONDS, You LOSE!", width / 3, height / 10);
    frameRate(2);
  }
  
  gabFan();
  gabGooseBod();
}

function gabGooseBod() {
  push(); //goose neck
  stroke(240);
  strokeWeight(30);
  line(0, windowHeight, mouseX-(mouseX/2), mouseY-25);
  pop();
  
  fill(240); //goose torso
  circle(0, windowHeight, 300);
  fill(300); //gooseHead
  rect(mouseX-(mouseX/2), mouseY-25, 50, 50); 
  circle(mouseX-(mouseX/2), mouseY-25, 100);
  fill(0);
  circle(mouseX-(mouseX/2), mouseY-25, 40); //eye
  fill(255,166,0);
  circle(mouseX-(mouseX/2)+50, mouseY, 50); //goose bill & mouth
  
  fill(300,0,0,laserHue);
  rect(mouseX-(mouseX/2), mouseY-40, mouseX-(mouseX/2), 30);
  if (mouseIsPressed === true) {
    laserHue = laserHue + 40;
  } else {
    laserHue = 0;
  }
}

function gabFan() {
  fill(220);
  rect(windowWidth/2,windowWidth/2,windowWidth/2,windowHeight/2);
  
  fill(0);
  textSize(windowWidth/20);
  text("Thermostat: " + gabThermoStat + "/100", windowWidth/2+25, windowHeight/2)
  gabThermoStat = gabThermoStat + 1;
  
  let button0 = createButton("-1"); //heats up
  // button.mouseClicked(fanButton[0]);
  button0.size(90, 70);
  button0.position(windowWidth/2, windowHeight/2);
  button0.style("font-size", "48px");
  
  let button3 = createButton("3"); //3 button
  button3.mousePressed(fanButton);
  print(button3.mousePressed(fanButton));
  button3.size(90, 70);
  button3.position(windowWidth/2, windowHeight/2 + 70);
  button3.style("font-size", "48px");
  
  let button2 = createButton("2"); //2 button
  // button.mouseClicked(fanButton[1]);
  button2.size(90, 70);
  button2.position(windowWidth/2, windowHeight/2 + 140);
  button2.style("font-size", "48px");
  
  let button1 = createButton("1"); //1 button
  // button.mouseClicked(fanButton[2]);
  button1.size(90, 70);
  button1.position(windowWidth/2, windowHeight/2 + 210);
  button1.style("font-size", "48px");
}

function fanButton() {
  gabThermoStat = gabThermoStat - 20;
  print("-20, temp lowered");
}

I was thinking it was the timer slowing things down but the lag still happened. Then maybe it could be the goose’s neck? Nope not that.

UI for dynamic AI Article Writer – AI Editor

On codecanyon there are projects such as MagicAI and DaVinci AI. They have dozens of functionalities. I’m interested in something like AI Editor which allows you to create articles.

I need to quickly create a module that will include basic functions such as:

  • possibility of basic editing of the article content (stored in database)
  • the ability to select a piece of text and generate new text for it/rewrite a piece of text (that is, it connects to openAI/other and generates new text for the selected piece)

Does anyone know of an open source project that allows for something like this?
Alternatively do you know place where can I buy not encrypted, open code to buy?

CeasarCipher Javascript

I am working on a function here and have tried lots of different ways to take the shifted word and preserve the casing . I have even tried a module so I went back to code.

My question here is I am trying to get off the ground with the proper logic to preserve the case comparing the old word to the new word and making a new text is not so good. I am getting to the goal but the text is getting duplicated. on the capitalized words with lowercase in random order.

How to do i got about this?

//import { replace, html } from "preserve-case-replace";
//const { default: replace } = require("preserve-case-replace");
//import replace from "preserve-case-replace";

function ceasarCiper(word,cipher){
    let answer = "";
    let word1 = word

    let trackCasing = []
    for (let i = 0; i < word1.length; i++){
        if (word1[i].match(/^[A-Z]*$/)){
            trackCasing.push(i)
        }
    }

    console.log(trackCasing)
    word = word.toLowerCase()

    //let alphabet =  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    let alphabet = "abcdefghijklmnopqrstuvwxyz"

    console.log(alphabet[23], "testing here")
    console.log(alphabet[0])
    
    let newWord = ""

    for (let j = 0; j < word.length; j++){
        if (!word[j].match(/[a-zA-Z]/i)){
            newWord += word[j]
        }
        for (let i = 0; i < alphabet.length; i++){
            if (alphabet[i] === word[j] && (i+cipher) > 25){
                let remainder = (i+cipher) - 25 
                newWord += alphabet[remainder-1]
            } else{
            if(alphabet[i] === word[j]){
                console.log(cipher)
                console.log(alphabet[i + cipher], i, i+cipher)
                newWord += alphabet[i+cipher]     }
                }
            };
        };

        console.log(trackCasing)

        newWord = newWord.split("")
        
    
        //console.log(answer)
        //replace(inputText, word. newWord)
        return newWord
    };


//console.log(ceasarCiper("hello", 2))
console.log(ceasarCiper("x?Y!Z", 3))

//failed test cases

 /* for (let i = 0; i < newWord.length; i++){
            for (let j = 0; j < trackCasing.length; j++){
                if (i === trackCasing[j]){
                    answer += newWord[i].toUpperCase()
                } 
                else(
                    answer += newWord[i]
                )
            }
        }
        answer = [...new Set(answer)].join("")*/


    /*let counter = trackCasing.length
        //string.replace(searchValue, replaceValue);
        while(counter){
        for (let i = 0; i < trackCasing.length; i++){
          console.log(trackCasing[i])
            
        
        let a = newWord.replace(newWord.charAt(trackCasing[i]), newWord.charAt(trackCasing[i]).toUpperCase())
    counter--    
    console.log(a)
        }
        
    }*/
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="" src="test4.js"></script>
    <title>Document</title>
</head>
<body>
    
</body>
</html>

If statement not working during a function call to update count during a specific time period [closed]

I am bit confused as to why this function is not working.
It is supposed to check if an input is during a certain time and update the count for that time period only. It should be a simple task but I might be overthinking this function.

the idea is that it will add count to specific time areas. so anything added during 10.00-11.00 will add up during that time slot and next it will add count in the next time slots.

function updateCount(){
    let min = d.getHours()
  if(time  > 10 && time < 11 ){
     barOne++;
    console.log('bar one: '+barOne);
     bar1.style.height= barOne*1+"em";
    localStorage.setItem("one", barOne)
  }
  else if(time > 11 && time < 12){
    barTwo++;
    console.log(barTwo) 
   
     bar2.style.height= barTwo*1+"em";
    localStorage.setItem("two", barTwo)
    
  }
   else if(time > 12 && time < 13){
    barThree++;
    console.log(barThree)
     bar3.style.height= barThree*1+"em";
     localStorage.setItem("three", barThree)
  }
  else if(time > 13 && time < 14){
    barFour++;
    console.log(barFour)
     bar4.style.height= barFour*1+"em";
    localStorage.setItem("four", barFour)
  }
  else if(time > 14 && time < 15){
    barFive++;
    console.log(barFive)
     bar5.style.height= barFive*1+"em";
    localStorage.setItem("five", barFive)
  }
  else if(time > 15 && time < 16){
    barSix++;
    console.log(barSix)
     bar6.style.height= barSix*1+"em";
    localStorage.setItem("six", barSix)
  }
  else if(time > 16 && time < 17){
    barSeven++;
    console.log(barSeven)
    localStorage.setItem("five", barSeven)
     bar7.style.height= barSeven*1+"em";
  }
  else if(time > 17 && time < 18){
    barEight++;
    console.log(barEight);
    localStorage.setItem('eight', barEight);
    bar8.style.height= barEight*1+"em";
  }
  else if(time > 18 && time < 19){
    barNine++;
    console.log(barNine);
    localStorage.setItem('nine', barNine);
    bar9.style.height= barNine*1+"em";
  }
  else{
    console.log(`it's ${min} it's outside range`)
  }
}

trying to the count to update a specific time period.