jquery adding classes on click – problem that checking and adding at the same time

On click on element a I add class “added_to_cart” with function “functionToAdd”
I also want to check If thisElement is already in cart with “added_to_cart”

Problem is that on click is adding class added_to_cart so alert is in case when element is not in cart and when it is, because in same time is checking and adding class.

jQuery("#element a").on("click", function() {

   var thisElement = jQuery(this).closest('#element');

   functionToAdd(thisElement);

   if (thisElement.hasClass("added_to_cart")) { 

       alert("already added to cart");

   }

})

I’m trying to avoid setTimeout function..
Thanks for help

Firebase storage api 10.6.0 web api upload image uploadBytes code pure javascript from cordovacamera plugin full working

This is not a question, I have really struggled to figure out how to implement a working code on pure javascript using the firebase web library, since google doesn’t really offer a clear documentation to help….So enjoy:

import {initializeApp} from 'https://www.gstatic.com/firebasejs/10.6.0/firebase-app.js';
import { getDownloadURL ,getStorage, ref, uploadBytes  } from "https://www.gstatic.com/firebasejs/10.6.0/firebase-storage.js";
const firebaseConfig = {
    apiKey: "",
    authDomain: "blahblah.firebaseapp.com",
    projectId: "blahblah",
    storageBucket: "blahblah.appspot.com",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
  };
const app = initializeApp(firebaseConfig);
const storage = getStorage(app);

var imgData = null;
var imageBlob = null;

function onSuccessCar(imageData) {
    
    imgData = imageData;
    // Convert base64-encoded image data to Uint8Array
    const imageDataByteArray = Uint8Array.from(atob(imgData), c => c.charCodeAt(0));    //Uint8Array.fromBase64(imageData);
    // Create a Blob object from the Uint8Array
    imageBlob = new Blob([imageDataByteArray], { type: 'image/jpeg' });
    console.log(imageBlob);
 }

 function onFailCar(message) {
    console.log("Picture failure: " + message);
}

window.openCamereCar = function openCamereCar(){
    
    navigator.camera.getPicture(onSuccessCar, onFailCar, {
        quality: 30,
        targetWidth: 2416,
        targetHeight: 3188,
        allowEdit: false,
        destinationType: Camera.DestinationType.DATA_URL,
        correctOrientation: true,
        encodingType: Camera.EncodingType.JPEG,
     });
     
}

window.UploadPicture = async function UploadPicture(event){
    event.preventDefault();
    if(imgData !== null){
        const fileName = [AnyRandomName]+'.jpg';
        const imageRef = ref(storage, 'car_certificates/'+fileName);

        uploadBytes(imageRef, imageBlob).then(() => {
            console.log('Image uploaded successfully!');
            // Get the URL of the uploaded image
            getDownloadURL(imageRef).then((url) => {
                console.log('Image URL:', url);
            })
        }).catch((error) => {
            console.error('Upload failed:', error);
        });
    }

}

I expected the documentation that google offers to be more helpful.
You can check this video here:
https://www.youtube.com/watch?v=-IFRVMEhZDc

React Virtuoso displays the list with a delay

I am using React Virtuoso to create a virtual list.
First, I’ll explain the scenario in which I use React Virtuoso. Then, I’ll outline my problem and explain how it is related to React Virtuoso. Finally, I’ll include a CodeSandbox to better simulate my issue

use scenario:
I have a track list, and I obtain this list from an API. I display a shimmer until I receive the API call response and then I display my list. For displaying this list I use React Virtuoso. I cant set a fixed height to my list and It has an auto height.

problem:
When the shimmer disappears and the list should be displayed, there is a delay between them. I believe it’s related to the way React Virtuoso works, and in my case, it causes a jump on my page. This delay is around 100ms or less but it results in an undesirable jump, causing a poor user experience.

First, I create a CodeSandbox out of my project to test the process of rendering in two different situations. The first one has a normal list, and the other one uses React Virtuoso for rendering the list.

After that, I open Chrome DevTools and its performance tab. Then, I record each list’s rendering process. In the pure list, there isn’t any delay between the shimmer disappearing and the list being displayed. However, in the list rendered with React Virtuoso, there is a delay
You can observe the Virtuoso list jumping in this Code Sandbox.
link to code example

iOS 17: changing contrast and darkness of canvas content – is this a bug?

I appologize beforehand as it is not a detailed question, but more of a general inquiry. The goal of this question is to find out whether this is an actual bug in iOS 17 and if so, where to best report this.

Since the update to iOS 17, the pictures in our virtual tours randomly turn very dark and high contrast. They are shown in a canvas so it looks like the entire canvas content is being manipulated. However nothing in our code does this, it happens very randomly (not in every picture and also not in the same pictures every time) and it’s only in iOS 17 (not in other iOS versions, Mac, Windows, Android, …).
We tried debugging for hours and hours but nothing indicates that this is caused by anything in our code.

To try it out yourself: visit https://youreka-virtualtours.be/tours/vyncke_buhler/

To see it in action:

non iOS 17: what it looks like on other devices

iOS 17:what it looks like on iOS 17

Angular auth guard not redirecting to login

I would like some help with troubleshooting an issue I have in my app. I am trying to create a functionality, that if the user is not loged in if he tries to access any url of the app he should be redirected to login.

I have created a auth guard but it somehow does not redirect me or users to www.my-domain.com/login but it rather stays on the www.my-domain.com/dashboard but it shows an empty page…

where is the issue in my code?

Here is the auth.service.ts code:

login(): Observable<User> {
    const params = new HttpParams().append('param', 'value');
    return this.http.get<User>(`${environment.apiUrl}someurl` + location.search, {params}).pipe(
      tap((response: any) => {
        if (response && response.token) {
          localStorage.setItem('TOKEN_KEY', response.token);
          localStorage.setItem('username',response.user_name);
          localStorage.setItem('useremail',response.user_email);
          this.setAuthToken(response.token);
          this.isLoggedIn = true;
        } else {
          this.router.navigate(['/login']);
          return;
        }
      }),
      catchError(error => {
        console.error('Error:', error);
        return throwError(error);
      })
    );
  }

  isLogedIn() {
    const token = localStorage.getItem('TOKEN_KEY');
    return !!token;
  }

Here is my auth.guard.ts code:

export const authGuard = () => {
  const authService = inject(AuthenticationService);
  const router = inject(Router);

  if (authService.isLogedIn()) {
    return true;

  } else {
    console.log('Not logen in');
    return router.parseUrl('/login');
  }

};

Where is my mistake? what could I have done diferently?

Combining a random quote generator with typewriter effect

So I’ve been playing around with a project that includes a random quote generator, and I was hoping to combine it with a simple typewriter-esque animation when the generator loads a new quote.

Problem is I know very little about javascript and basically have no idea what I’m doing, which makes it hard to implement other people’s similar-but-not-quite-it solutions.

The basics of the code is this;

const generateQuote = function() {
  const quotes = [{
      quote: "Here's a text",
    },
    {
      quote: "Here's another one",
    },
    {
      quote: "Lorem ipsum bla bla",
    },
    {
      quote: "I can do this all day",
    }
  ];

  let arrayIndex = Math.floor(Math.random() * quotes.length);
  document.getElementById("quotetxt").innerHTML = quotes[arrayIndex].quote;
}

window.onload = function loadquote() {
  generateQuote();
  document.getElementById("generate").addEventListener('click', generateQuote);
}
<p id="quotetxt"> </p>
<button id="generate">generate</button>

I’ve tried combining it with scripts for typewriter effects I’ve seen around (like the basic one on W3schools), but I can’t figure out how to make it work like I want. I can make the initially loaded quote appear with the animation, or animate single texts, but not from a random array on button press like I want.

At one point I managed to somehow make the quote generator scramble all the letters in the quotes, though I have no idea how I did that and I didn’t keep the code.

I’ve seen some jquery stuff around for typewriter effects, but they all seem far more advanced than what I’m looking for, but if there’s a simple one you could recommend that would be fine too.

(I’m also completely new to stackoverflow, I did my best to follow the guidelines but I apologise if I missed something)

Did anyone solve this error: Failed to load resource: the server responded with a status of 403() while trying to login with google?

I have been trying to introduce an option to log in with google using my webpage and using vue3, google console and the library ‘vue3-google-signin’ but am unable to make the code work beacuse of that problem and ‘m=credential_button_library:48 [GSI_LOGGER]: The given origin is not allowed for the given client ID.’ this one, could anyone help me?

When I press the button I created I am actually able to open a new tab with https://accounts.google.com/ but the content is empty, I am supposing that the problem came from the errors I wrote.

This id the code:

<template>
  <GoogleSignInButton
    @success="handleLoginSuccess"
    @error="handleLoginError"
  ></GoogleSignInButton>
  <!-- You can add more UI elements here as needed -->
</template>

<script setup>
import { GoogleSignInButton } from 'vue3-google-signin';

const handleLoginSuccess = async (response) => {
  const { credential } = response;
  console.log("Access Token", credential);

  try {
    // Send the credential to your backend for verification and user identification
    // Assume authenticateUser is a method that does this
    const user = await authenticateUser(credential);
    // Store user information in local storage or a global state
    localStorage.setItem('user', JSON.stringify(user));
    // Update UI to reflect user is logged in
    // This could be showing a logout button, user info, etc.
  } catch (error) {
    console.error("Authentication error:", error);
    // Handle authentication errors
    // Update UI to reflect error
  }
};

const handleLoginError = (error) => {
  console.error("Login failed:", error);
  // Update UI to inform user about the login failure
  // This could be showing an error message to the user
};
</script>

Make a button that increments numbers on every click [duplicate]

Here is my html and JavaScript code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>People Increment</title>
  

<script>
    let countEl = document.getElementById("count-el")
    console.log (countEl)
    let count = 0;

    function increment() {
        count = count + 1;
        console.log(count)
        countEl.innerText= count
    }
</script>

</head>
<body>

    <h1>Lets See How Many Time You've Have Clicked On this Button</h1>
    <h1 id="count-el"></h1>
    <button onclick="increment()">Increment</button>

</body>
</html>

when I remove the line

countEl.innerText= count.

It shows the right output but in console-inspect menu. Need a solution that somehow don’t use EventListner

How do i divide my mapped data in pages and place footers on all pages in react-to-print

I am using react-to-print to generate an invoice in which the table data is being mapped. As the mapped content increases it pushes down the footer with no proper placement. I want to place the footer on every page and I also want to show the page number there. How can I do this?

I have been stuck and have tried different CSS properties like absolute and fixed placement of the footer but obviously they are not working. Obviously this issue wont be solved by CSS alone.

<div className="invoice__preview bg-white p-5 rounded-2xl border-4 border-blue-200  ">
    <ReactToPrint
        trigger={() => (
            <button className="bg-blue-500 ml-5 text-white font-bold py-2 px-8 rounded hover:bg-blue-600 hover:text-white transition-all duration-150 hover:ring-4 hover:ring-blue-400">
                Print / Download
            </button>
        )}
        content={() => componentRef.current}
    />
    <div ref={componentRef} className="py-5 px-8 flex flex-col min-h-full relative">
        <div>
            <div className=" flex justify-between my-5">
                <article className=" flex items-start justify-start">
                    <ul>
                        <li className="p-1 ">
                            <span className="font-bold">Location:</span> {location}
                        </li>
                        <li className="p-1 ">
                            <span className="font-bold">To:</span> {rowData.firstname + ' ' + rowData.lastname}
                        </li>
                    </ul>
                </article>
                <article className=" flex flex-col gap-2 items-start justify-end rounded-lg border border-black px-3 py-3">
                    <h2 className=" font-bold">Statements of Accounts (Period)</h2>
                    <ul>
                        <li className=" ">
                          <span className="">From Date:</span> {fromDate}
                        </li>
                        <li className=" ">
                          <span className="">To Date:</span> {toDate}
                        </li>

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

            <table width="100%" className="mb-10 ">
                <thead>
                    <tr className="bg-gray-100 p-1 py-2 text-base text-black border-t border-b border-black uppercase w-full font-semibold">
                        <td className="font-bold">DATE</td>
                        <td className="font-bold">DOC NO</td>
                        <td className="font-bold">NARRATION</td>
                        <td className="font-bold">DEBIT</td>
                        <td className="font-bold">credit</td>
                        <td className="font-bold">balance</td>
                    </tr>
                </thead>
                {clientData && clientData.length > 0 ? (
                    <tbody>
                        <tr className=" h-10 font-bold rounded-xl border border-black">
                            <td></td>
                            <td></td>
                            <td>Opening Balance as on  {formatDate(new Date(fromDate))}</td>
                            <td></td>
                            <td></td>
                            <td>{clientData[0].Balance}</td>
                        </tr>
                        {clientData.map(({ date, docid, description, debit, credit, Balance }, index) => {

                        const formattedDate = formatDate(date);

                        return (
                            <tr key={docid} className="h-10">
                            <td>{formattedDate}</td>
                            <td>{docid}</td>
                            <td>{description}</td>
                            <td>{debit}</td>
                            <td>{credit}</td>
                            <td>{Balance}</td>
                            </tr>
                        );
                        })}

                        <tr className="h-10 font-bold rounded-xl border border-black">
                        <td></td>
                        <td></td>
                        <td>Transaction Totals:</td>
                        <td className="underline">{Math.round(clientData.reduce((total, { debit }) => total + parseFloat(debit || 0), 0))}</td>
                        <td className="underline">{Math.round(clientData.reduce((total, { credit }) => total + parseFloat(credit || 0), 0))}</td>
                        <td></td>
                        </tr>
                    </tbody>
                    ) : (
                    <p className="mx-auto">No data available</p>
                    )}
            </table>

        </div>

        <footer className= " mt-auto footer border-t-2 border-gray-300 pb-5">
            <div className=" w-full flex justify-evenly pt-4 pb-14 px-5 border-b border-gray-300 mb-2 text-base">
                <p>Prepared By</p>
                <p>Approved By</p>
                <p>Salesman</p>
                <p className=" ">Reciever's Name & Signature </p>
                <p>Store Keeper</p>

            </div>
            <ul className="flex flex-wrap items-center gap-2 justify-center">
                <li>
                    <span className="font-bold">Email:</span> {"[email protected]"}
                </li>
                <li>
                    <span className="font-bold">Tel:</span> {""}<span className="ml-1 font-bold">-Fax:</span> {""}
                </li>
                <li>
                    <span className="font-bold">P.O Box:</span> {" "}
                </li>
            </ul>
            <p className="text-center px-5 mt-4 text-xs ">
            Thankyou for your purchase!
        </p>
        </footer>
    </div>
</div>

Javascript heap out of memory when building

I’m receiving the error below when trying to build and deploy our react application.

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory

Whereas I think that this is purely a JavaScript issue, I’m not sure whether I can rule out anything related to our cloud setup: A bit bucket pipeline which pushes the bundle to an S3 bucket (AWS) and is exposed via a Cloudfront distribution (AWS).

I’ve searched for a solution, and saw that this could be solved by increasing the max_old_space_size. I changed the react scripts as follows (added –max_old_space_size=6000), but this did not do the trick.


  "scripts": {
     ...
    "build:dev": "REACT_APP_ENV=development npm run build --max_old_space_size=6000",
   }

Any help would be incredibly helpful

Read environment variables from a database Node JS [closed]

I have a Node JS application that works well with the environment variables saved in the .env file.

I would like some data saved from the frontend in the database to be read as environment variables. So, when the application is launched, the data is retrieved from the database and loaded as environment variables.

How to initialize empty array of objects in vue3

I am using Vue3 with Nuxt. I want to initialize an empty array of objects, and then set it.

let results = ref([]);
        results.value = [
            {
                "name": input.value,
            }
        ]

However I am getting an error
Type '{ name: string; }' is not assignable to type 'never'.

I tried this
let results: any[] = ref([]);

And looked at v-for documentation in vue. But the example initializes a non-empty array of objects
const items = ref([{ message: 'Foo' }, { message: 'Bar' }])
https://vuejs.org/guide/essentials/list.html#v-for

Getting error while upgrading my reactjs project with node version 18

I am unable to update my reactjs project from v16 to 18 and also facing this gyp error when I try to upgrade, I tried sass instead of node-sass.


SyntaxError: EOL while scanning string literal
gyp ERR! configure error 
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/projectPath/node_modules/node-gyp/lib/configure.js:345:16)
gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:291:12)
gyp ERR! System Darwin 23.1.0
gyp ERR! command "/usr/local/Cellar/node@18/18.16.0/bin/node" "/projectPath/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /projectPath/node_modules/node-sass
gyp ERR! node -v v18.16.0````

thanks for the help in advance.