I Linked local jquery files in my next js 14 project in layout.js, some time it worked but some time it gave me errors like jquery not define

**when i load project gave me errors like

jqery not define,
Unhandled Runtime Error
TypeError: a is not a function

and when i refresh page multiple time some time it worked and some time start giving me same erros
**

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <Providers>
        <body className={inter.className}>
          <Header />
      
          {children}
          <Footer />
          <Script src="/assets/js/jquery.min.js" />
          <Script src="/assets/js/bootstrap.bundle.min.js" />
          <Script src="/assets/js/magnific-popup.min.js" />
          <Script src="/assets/js/main.js" />
          <Script src="/assets/js/meanmenu.js" />
          <Script src="/assets/js/nice-select.min.js" />
          <Script src="/assets/js/owl.carousel.min.js"   />
        </body>

      </Providers>
    </html>
  )
}

code projct folder structure

Chrome url throttler extension

There is an extension for delaying requests. The problem is that it doesn’t work with parallel requests. That is, if we set a mask for a domain, then we must wait until the files of images, styles, scripts, etc. are loaded one by one. There are 2 main files in the extension:

background.js

const delay = (ms) => {
  const startPoint = new Date().getTime()
  while (new Date().getTime() - startPoint <= ms) {/* wait */}
}

let handler;
chrome.storage.onChanged.addListener(function(changes, namespace) {
  if (changes.hasOwnProperty('requestThrottler')) {
    const throttlerConfig = changes.requestThrottler.newValue;
    if (handler) {
      chrome.webRequest.onBeforeRequest.removeListener(handler);
      handler = null;
    }

    const urls = throttlerConfig.urls.filter((u) => !u.error && u.url !== '').map((u) => u.url.trim());
    if (throttlerConfig.enabled && urls.length > 0) {
      chrome.browserAction.setIcon({path: 'icon48-warning.png'});
      handler = (info) => {
        console.log(`URL Throttler: Intercepted ${info.url}, going to wait ${throttlerConfig.delay} ms...`);
        delay(throttlerConfig.delay);
        console.log('URL Throttler: Done');
        return;
      };
      console.log('Blocking urls', urls);
      chrome.webRequest.onBeforeRequest.addListener(
        handler,
        // filters
        {
          urls: urls,
        },
        // extraInfoSpec
        ["blocking"]
      );
    } else {
      chrome.browserAction.setIcon({path: 'icon48.png'});
    }
  }
});

popup.js

const defaultURL = {
  url: '',
  error: false,
};
const urlRegex = /^(https?|*)://.*/.*$/;

chrome.storage.local.get(['requestThrottler'], (result) => {
  const data = Object.assign(
    {}, {
      enabled: false,
      urls: [{ ...defaultURL }],
      delay: 5000,
    },
    result.requestThrottler
  );
  var app = new Vue({
    el: '#app',
    data: data,
    methods: {
      addUrlInput: function() {
        this.urls = this.urls.concat({ ...defaultURL });
      },
      removeUrlInput: function(index) {
        this.urls.splice(index, 1);
      },
      updateStorage: _.debounce(function() {
        this.urls = this.urls.map((u) => {
          return {
            ...u,
            error: !urlRegex.test(u.url),
          };
        });
        chrome.storage.local.set({requestThrottler: {
          enabled: this.enabled,
          urls: this.urls,
          delay: this.delay,
        }});
      }, 700),
    },
    updated: function() {
      this.updateStorage();
    }
  });
});

My question is how to remake the script so that requests are processed in parallel?

ChatGPT cannot write an exact solution, although it gives seemingly working advice:

The problem is that the handler that is registered via chrome.webRequest.onBeforeRequest.addListener is executed synchronously for each request.

This means that when parallel requests are received to two different URLs from the list, the handler blocks the execution of the first request for delay, then unblocks and blocks the second request also for delay.

In order for requests to be processed in parallel, you need to move the delay logic into a separate asynchronous function.

But for some reason he can’t write a working function…

How to handle databases when testing with supertest?

I can’t find a conclusive answer to this. I don’t know if I should use the production DB and delete the test documents that were created when all tests are run, or if I should make a clone of the DB and use that for testing, to avoid any unwanted behavior.

For now, I’ve been using the production DB and what I do is put the tests in this order: POST, GET, PATCH, DELETE. This way the DELETE test gets rid of the document created during the previous test/s. This works fine generally, but I’m pretty sure it is not a good practice.

Showing blank page after npm start, the browser did not show any error message

Showing blank page after npm start, the browser did not show any error message.

import {
  createBrowserRouter,
  RouterProvider,
  Route,
  Outlet,
} from "react-router-dom";
import './App.css';
import * as React from "react";
import Register from "./pages/Register"
import Login from "./pages/login"
import Write from "./pages/Write"
import Home from "./pages/home"
import Single from "./pages/single"
import Footer from './components/Footer';
import Navbar from './components/navbar';
import "./project.scss"

const main = () => {
  return (
    <div>
      <Navbar />
      <Outlet />
      <Footer />
    </div>
  )
};

const router = createBrowserRouter([
  {
    path: "/",
    element: <main />,
    children: [
      {
        path: "/",
        element: <Home />,
      },
      {
        path: "/post/:id",
        element: <Single />,
      },
      {
        path: "/write",
        element: <Write />,
      },
    ],
  },
  {
    path: "/register",
    element: <Register />,
  },
  {
    path: "/login",
    element: <Login />,
  },

])

function App() {
  return (
    <div className="app">
      <div className='container'>
        <RouterProvider router={router} />
      </div>
    </div>
  );
}

export default App;

Also I get this warning message in the VS Code:

WARNING in [eslint]
srcApp.js
  Line 4:3:   'Route' is defined but never used          no-unused-vars
  Line 21:7:  'main' is assigned a value but never used  no-unused-vars

I am also get lost on this. How the main is not used?

I have tried multiple solutions that I have found but none of them have worked yet. I know it is the path issue, but don’t know how to get it working. I want to keep the children elements.

How can I send the product IDs for an item array back to Pinterest?

I’m attempting to create a Checkout event to send to Pinterest Ads. I’m using custom javascript to transform my data, in particular I need to sum the item totals and total cart value since these are not being passed through the data layer.

I’ve been able to write the custom javascript for majority of all needed parameters for Pinterest except the product ID. The system is not picking it up in the array. I’ve tried seeing if I could get either the product name or product id to pass through. I initially tried id: items[i].id and the system wasn’t picking it up, so i’ve since tried product_id: items[i].id, and still no luck.

function() {
  var items = {{dlv - olo - all products}};
  var numItems = 0;
  var totalValue = 0;
  var transformedItems = [];

  for (var i = 0; i < items.length; i++) {
    transformedItems.push({
      product_id: items[i].id,
      product_name: items[i].name,
      product_category: 'product',
      quantity: items[i].quantity,
      price: items[i].price
    });
    numItems += items[i].quantity;
    totalValue += items[i].price
  }
  
  return {
    value: totalValue,
    currency: 'USD',
    line_items: transformedItems,
    order_quantity:  numItems,
    order_id: {{dlv - olo - transaction ID}}
  };
}

Here is the GTM custom HTML tag that I’m using to pull in the cjs:

<!-- Pinterest Pixel Code -->
<script>  
  pintrk('track', 'checkout', {{cjs - Pinterest Data For Purchases}})
</script>
<!-- End Pinterest Pixel Code -->

Here is the data layer push:

{
    event: "begin_checkout",
    ecommerce: {
        items: [
            {
                item_id: "42353541",
                item_name: "Avocado Hummus",
                currency: "USD",
                price: 8,
                quantity: 1
            },
            {
                item_id: "41371457",
                item_name: "Avocado Caesar Salad",
                currency: "USD",
                price: 10.95,
                quantity: 1
            }
        ]
    }
}

How to create visit counter when a website load

I need to create a counter for a website. Every time the visitor Number Increasing when the page load and save this counter on server. In stackoverflow, I have searched many answer with this regard but not succeed.

Is there a full work around code in html, javascript, php etc. ?

Detect and remove prev/next arrows if there’s more than one image

This is a slideshow HTML that’s generated with 3 images and shown are the Prev << and Next >> buttons.

<div class="wp-block-gallery">
    <div class="wpcookie-slide"> 
        <img decoding="async" loading="lazy" src="image1.jpg" alt="image"> 
    </div>
    <div class="wpcookie-slide"> 
        <img decoding="async" loading="lazy" src="image2.jpg" alt="image"> 
    </div>
    <div class="wpcookie-slide"> 
        <img decoding="async" loading="lazy" src="image3.jpg" alt="image">
    </div>
    <span class="wpcookie-controls wpcookie-left-arrow"> << Prev </span> 
    <span class="wpcookie-controls wpcookie-right-arrow"> Next >> </span> 
</div>

I want to hide the << Prev & Next >> buttons when there’s just 1 image in the slideshow. It creates a bad UX for the users to show the arrows when there’s only 1 image in the slideshow.

Here’s the JS code that generates the slideshow:

document.querySelectorAll(".wp-block-gallery")?.forEach( slider => {
  var src = [];
  var alt = [];
  var img = slider.querySelectorAll("img");
  img.forEach( e => { src.push(e.src);   if (e.alt) { alt.push(e.alt); } else { alt.push("image"); } })
  let i = 0;
  let image = "";
  let myDot = "";
  src.forEach ( e => { image = image + `<div class="wpcookie-slide" > <img decoding="async" loading="lazy" src="${src[i]}" alt="${alt[i]}" > </div>`; i++ })
  i = 0;
  src.forEach ( e => { myDot = myDot + `<span class="wp-dot"></span>`; i++ })
  let dotDisply = "none";
  if (slider.classList.contains("dot")) dotDisply = "block";    
  const main = `<div class="wp-block-gallery">${image}<span class="wpcookie-controls wpcookie-left-arrow"> << Prev </span> <span class="wpcookie-controls wpcookie-right-arrow"> Next >> </span></div> `       
  slider.insertAdjacentHTML("afterend",main  );
  slider.remove();
})
document.querySelectorAll(".wp-block-gallery")?.forEach( slider => { 
  var slides = slider.querySelectorAll(".wpcookie-slide");
  var dots = slider.querySelectorAll(".wp-dot");
  var index = 0;
    slider.addEventListener("click", e => {if(e.target.classList.contains("wpcookie-left-arrow")) { prevSlide(-1)} } )
    slider.addEventListener("click", e => {if(e.target.classList.contains("wpcookie-right-arrow")) { nextSlide(1)} } )
  function prevSlide(n){
    index+=n;
    console.log("prevSlide is called");
    changeSlide();
  }
  function nextSlide(n){
    index+=n;
    changeSlide();
    }
    changeSlide();
  function changeSlide(){   
    if(index>slides.length-1)
      index=0;  
    if(index<0)
      index=slides.length-1;  
      for(let i=0;i<slides.length;i++){
        slides[i].style.display = "none";
        dots[i].classList.remove("wpcookie-slider-active");      
      }
      slides[index].style.display = "block";
      dots[index].classList.add("wpcookie-slider-active");
    }
})

JS frameworks with dynamic binding and partial array rerenders?

I have mainly developed C# and am used to things like ObservableCollections which allow to rerender only changed / new / removed elements of arrays.

I am about beginning a web-based project (node backend + webpage) where usually small (20-100 items), but also large datasets (up to 500 – 750 items) should be rendered with dynamic bindings, paging is for different reasons not wanted.

I searched a lot and although found some frameworks like ReactJS, Vue and others that supports dynamic bindings, but as far I understood, none of them support partial rerenders of only the changed array items, which could be a performance problem.

Do such JS frameworks exists I am searching for?
Or would be better in this case to use a different approach?

JS code does not print any output when it’s supposed to

So, my JS code doesn’t run because of an error, and I have no idea what the error is.
Here’s the code:

javascript

var name = 'anyName'
var score = 0

if (score < 1) {
    function1()
}

function function1() {
    prompt('Enter something')
    score++;
    function2()
}

function function2() {
    if (score < 100 && score < 300) {
        function1()
    }
}

while (score < 9000 && true) {
    function1()
}

print("Your score is: " + score + ". Your username: " + name + ".")

It’s not in an html code so I have NO idea what’s going on.

I was expecting the following output:

Your score is: score. Your username: name.

If there is an answer, I would appreciate it.

setTimeout and setInterval time management

I want to create a function that prints ‘Hello, World!’ every second for 5 minutes, and after 5 minutes, this function will stop for 1 minute. I want to create a loop like this with setTimeout and setInterval, but I couldn’t. Can anyone help me?

const helloWorld = () => console.log("Hello, World!")

const stopSayHello = () => console.log("Stopped for a minute!")

The HelloWorld function will run every second for 5 minutes. After 5 minutes, the stopSayHello function will run for a minute. Then, this loop will continue.

Typescript, ts-jest import .ts file instead of .js file with same names

I have a test file and the file that test imports. Something like:

// fileA.spec.ts

import fileA from "services/fileA"

// do stuff....

Now I have another build process that may run and will generate the equivalent JS file which leaves me with a file structure that looks like

src
- services
-- fileA.ts
-- fileA.js --> this is generated by a build script
-- fileA.spec.ts

If I run my jest test before running the script that creates the JS file, the tests run fine and pass. However, if I run them after then the import tries to import the JS file and causes errors.

How can I configure typescript or TS-jest to resolve imports to TS files and ignore JS files ?

animation problem when value changes while setTimeout timer’s running

function wallpaperMediaPropertiesListener(event) {

    // reset animation
    test.stop(true);
    test.css('margin-left', 0);
    
    // set song title.
    test.text(event.title);
    var testWidth = test.outerWidth();
    
    // clone text
    $('.test-copy').remove();
    if (testWidth > $('#line1').width()) {
        test.clone().css({'margin-left': gap, 'font-size': '1.05vh'}).removeClass().addClass('test-copy').insertAfter(test);
    }
    
    // move text
    let speed = 5;
    function shiftingAnimation() {
        let timer = setTimeout(() => {
            test.animate({'margin-left': -(testWidth + gap)}, {
            duration: Math.abs((testWidth + gap) * 100 / speed),
            easing: 'linear',
            complete: function () {
                test.css({'margin-left': 0});
                clearTimeout(timer);
                shiftingAnimation();
            }
            });
        }, 3000);
    }

    // first execution
    if (testWidth > $('#line1').width()) {
        setTimeout(shiftingAnimation, 3000);
    }

}

event.title returns song name that is playing.
wallpaperMediaPropertiesListener function will be triggered when song changes.

animation starts after 3s delay when testWidth > #line1 width. when animation ends, it repeats itself with 3s delay each time. if event.title value changes, it resets animation and start from first 3s delay and so on.

but when event.title value changes while setTimeout timer in if statement is running, it ignores if statement or first 3s delay and applies animation to it even if condition is false (not certain what is actually happening but at least it looks like it).

Troubleshooting Integration Issues with One tap Google Sign-In Button on a Website

As part of a university assignment, I’ve been attempting to integrate the One Tap Google Sign-In button into a website. Initially, the button was not functioning properly on a local server via Visual Studio Code. To troubleshoot, I deployed my project on GitHub Pages, which slightly improved the situation. However, a significant issue persists: on the first click, the account selection window appears, and after choosing an account, it only shows a loading screen without further progress. Subsequent attempts to click the button result in a loading screen without the account selection option, leading to no further action. Below, I will attach screenshots of my configuration in the Google Console and the relevant code snippets for further insight. I really need professional help. Thanks in advance for your answer.

<!DOCTYPE HTML>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <meta name="google-signin-client_id" content="my_id_here"/>
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <title>Prihlásenie pomocou Google API</title>
  </head>
  <body>
    <div id="content">
      <p>Sign in:</p>
      <div class="g-signin2" data-onsuccess="onSignIn"></div>
    </div>
    <script>
      function onSignIn(googleUser) {
        let profile = googleUser.getBasicProfile();

        console.log('Úplné meno: ' + profile.getName());
        console.log('Meno: ' + profile.getGivenName());
        console.log('Priezvisko: ' + profile.getFamilyName());
        console.log("Obrázok profilu: " + profile.getImageUrl());
        console.log("Email: " + profile.getEmail());

        let id_token = googleUser.getAuthResponse().id_token;
        console.log("ID Token: " + id_token);

        document.querySelector("#content").innerHTML = "<p>Hello " + profile.getGivenName() + "! Click to <a href='#' onclick='signOut();'>sign out</a>.</p>";
      }

      function signOut() {
        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () {
          alert("err");
          location.reload();
        });
      }
    </script>
  </body>
</html

in google console to Ouath 2 all that i write
Authorized JavaScript origins – https://{here-nick-name}.github.io
Authorized redirect URIs – the sae link

why is my reducer function getting called multiple times?

my reducer function as per seen the code below, is getting called multiple times causing my incremention to be worng and increment by margins of 2.
i am running this in strictmode so i know it renders one more time to be safe. but it shouldnt affect the state/

export const ItemContext = createContext();
export const CartItemContext = createContext();

function reducer(state,action){
  if(action.type === "increment-quantity")
  {
    console.log(state[action.mealIndex][1]);
    state[action.mealIndex][1] +=1 ;
  }
  else if(action.type === "decrement-quantity")
  {

  }
  else if(action.type === "add-meal")
  {
      state = [...state,[action.meal,1]];
  }
  return state;
}


function App() {
  const [orderedMeals,dispatch] = useReducer(reducer,[]);
  const [openModal,setOpenModal] = useState(false);
  const [Quantity,setQuantity] = useState(0);

  const [isFetching,menu,setFetchedData,error]= useFetch(fetchMeals,[]);



  const onAddToCart = (meal) => {
    const mealFound = orderedMeals.find((mealPair) => {return mealPair[0] === meal;})
    const mealIndex = orderedMeals.indexOf(mealFound);
    if(mealFound === undefined)
    {
      dispatch({type:"add-meal",meal:meal})
    }
    else
    {
      dispatch({type:"increment-quantity",mealIndex:mealIndex});
    }
    setQuantity(Quantity+1);
  };

i dont know hwo to fix this please help thank.

How to stop a sprite from moving off of a canvas in native JavaScript?

I’m currently creating a game in native JavaScript, HTML, and a bit of CSS. I have 2 blocks named Sprites and whenever they go toward the left or right edge of the canvas, they don’t stop. Question: How can I use native JS to stop the sprites from moving off the canvas?

Note: All answers to this solution are in other languages or use libraries, so this question has not been answered.

const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext("2d");

canvas.width = 1024;
canvas.height = 576;

function logMessage(msg) {
    document.querySelector('#myMessage').textContent += msg + '. ';
}

//This creates a background
ctx.fillRect(0, 0, canvas.width, canvas.height);

//Cahnging this value changes how fast the sprites fall
const gravity = 0.7;

class Sprite {
    //The curly braces makes it easier to pass values back and forth
    constructor({position, velocity}) {
        this.position = position;
        this.velocity = velocity;
        this.height = 150;
        this.lastKey;
    }

    draw() {
        ctx.fillStyle = 'red';
        //Because this is inside of the class "Sprite",
        //We can use "this." to give us the position/velocity/whatever that is being used in this instance
        ctx.fillRect(this.position.x, this.position.y, 50, this.height);
    }

    update() {
        this.draw();
        this.position.x += this.velocity.x;
        this.position.y += this.velocity.y;

        //Stops the sprite from moving off the edge of the canvas
        if (this.position.x <= 0 || this.position.x + 50 >= canvas.width) {
            logMessage("Hi")
            this.velocity.x == 0;
        }

        //Stops the velocity in the y direction if the sprite hits the bottom
        if (this.position.y + this.height + this.velocity.y >= canvas.height) {
            this.velocity.y = 0;
        } else {
            this.velocity.y += gravity;
        }
    }
}

const Player = new Sprite({
    position: {
        x: 0,
        y: 0
    },
    velocity: {
        x: 0,
        y: 0
    }
})

const Enemy = new Sprite({
    position: {
        x: 400,
        y: 100
    },
    velocity: {
        x: 0,
        y: 0
    }
})

const keys = {
    w: {
        pressed: false
    },
    a: {
        pressed: false
    },
    d: {
        pressed: false
    },
    ArrowUp: {
        pressed: false
    },
    ArrowLeft: {
        pressed: false
    },
    ArrowRight: {
        pressed: false
    }
}

function animate() {
    //This makes the animate method run over and over
    window.requestAnimationFrame(animate);
    //The two below fill in the background so that when the sprites move, the background stays the same
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    Player.update();
    Enemy.update();

    //Player movement
    Player.velocity.x = 0; //This stops the sprite from continuously moving

    if (keys.a.pressed == true && Player.lastKey == "a") {
        Player.velocity.x = -5; //Changing this value will change how fast the sprite moves left
    } else if (keys.d.pressed == true && Player.lastKey == "d") {
        Player.velocity.x = 5;
    }

    //Enemy movement
    Enemy.velocity.x = 0;

    if (keys.ArrowLeft.pressed == true && Enemy.lastKey == "ArrowLeft") {
        Enemy.velocity.x = -5;
    } else if (keys.ArrowRight.pressed == true && Enemy.lastKey == "ArrowRight") {
        Enemy.velocity.x = 5;
    }
}

animate();

//Event listeners that move the player when certain keys are pressed
window.addEventListener('keydown', (event) => {
    switch (event.key) {
        //Player movement
        case 'w':
            Player.velocity.y = -20;
        break;

        case 'a':
            keys.a.pressed = true;
            //This keeps track of our last pressed key so our sprite does what was pressed most recently
            Player.lastKey = "a";
        break

        case 'd':
            keys.d.pressed = true;
            Player.lastKey = "d";
        break;
    }

    //Enemy movement
    switch (event.key) {
        case 'ArrowUp':
            Enemy.velocity.y = -20;
        break;

        case 'ArrowRight':
            keys.ArrowRight.pressed = true;
            Enemy.lastKey = 'ArrowRight'
        break

        case 'ArrowLeft':
            keys.ArrowLeft.pressed = true;
            Enemy.lastKey = 'ArrowLeft'
        break;
    }    
})

window.addEventListener('keyup', (event) => {
    //Player keys
    switch (event.key) {
        case 'w':
            keys.w.pressed = false;
        break;    

        case 'a':
            keys.a.pressed = false;
        break

        case 'd':
            keys.d.pressed = false;
        break;
    }

    //Enemy keys
    switch (event.key) {
        case 'ArrowUp':
            keys.ArrowUp.pressed = false;
        break;    

        case 'ArrowLeft':
            keys.ArrowLeft.pressed = false;
        break

        case 'ArrowRight':
            keys.ArrowRight.pressed = false;
        break;
    }
})
#myConsole {
    background-color: black;
    color: white;
    min-height: 100px;
}
<!DOCTYPE html>
<html lang="en">

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE-edge">
        <meta name="viewport", content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Christian Davis">
        <link rel="stylesheet" href="styles.css">

        <title>Fighting Game</title>
    </head>

    <body>
        <canvas id="canvas"></canvas>
        
        <p id="myConsole">&gt;&nbsp;<span id="myMessage"></span></p>

        <script src="app.js"></script>
    </body>
</html>