How Add Leading Zero of hours, minutes and seconds

var countDownDate = new Date("October 31, 2024 14:00:00").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

Please Help me.

I have already tried this. Do I have a thought error?

function addZero(X){
if(X<10)
return "0"+X;
else
return X;
}

How can I redirect from a WebView back to my app after saving data (avatar) to Firestore?

I’m using a WebView in my Flutter app to allow users to create avatars via Ready Player Me. After the avatar is created, I save the avatar URL to Firestore. Once that’s done, I want to redirect the user back to my app (navigate to a specific screen).

Has anyone implemented something similar or have ideas on how to handle this redirect? Any suggestions or examples would be appreciated!

here is my firebase function
`
// Inject the currentUserUid into the JavaScript context
const currentUserUid = “${currentUserUid}”; // Ensure it’s passed as a string
const storeAvatarApi = “${storeAvatarApi}”;

    const frame = document.getElementById('frame');
    const loading = document.getElementById('loading');

    function displayIframe() {
      frame.src = `https://${subdomain}.readyplayer.me/avatar?frameApi=${token}`;
      frame.hidden = false;
    };
      
    window.onload = displayIframe;

    window.addEventListener('message', (event) => {
      const json = parse(event);

      if (json?.source !== 'readyplayerme') {
        return;
      }

      // Subscribe to iframe events
      if (json.eventName === 'v1.frame.ready') {
        frame.contentWindow.postMessage(
          JSON.stringify({
            target: 'readyplayerme',
            type: 'subscribe',
            eventName: 'v1.**'
          }),
          '*'
        );
      }

      // Capture avatar URL when the avatar is exported
      if (json.eventName === 'v1.avatar.exported') {
        const avatarUrl = json.data.url;
        window.parent.postMessage({type: 'AVATAR_CREATED', url: avatarUrl}, '*');
        console.log('Avatar URL:', avatarUrl, 'for user:', currentUserUid);
        saveAvatarUrlToFirestore(currentUserUid, avatarUrl);
        frame.hidden = true; // Hide iframe after avatar is exported
        window.location.href = `https://app.flutterflow.io/avatarCreated?avatarUrl=${encodeURIComponent(avatarUrl)}`;

      }

      // Handle user set event (optional)
      if (json.eventName === 'v1.user.set') {
        console.log(`User with id ${json.data.id} set: ${JSON.stringify(json)}`);
      }
    });

    // Helper function to parse postMessage events
    function parse(event) {
      try {
        return JSON.parse(event.data);
      } catch (error) {
        return null;
      }
    } 

    // Function to save avatar URL to Firestore or Firebase
    async function saveAvatarUrlToFirestore(currentUserUid, avatarUrl) {
      const response = await fetch(storeAvatarApi, { 
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ currentUserUid, avatarUrl }), // Ensure structured payload
      });
      
      if (response.ok) {
        console.log('Avatar URL saved successfully.');
       re
      } else {
        console.error('Error saving avatar URL:', response.statusText);
      }
    }
  </script>              `

Element overrining while pushing element

let header = [];

for (let index = 0; index < 4; index++) {
  header.push(`header${index}`);
}

let datacell = [];

for (let index = 0; index < 64; index++) {
  datacell.push(`datacell${index}`);
}

let Data = [];

let tempObj = {};

for (let j = 0; j < datacell.length; j++) {
  for (let k = 0; k < header.length; k++) {
    if (j % header.length === k) {
      tempObj[header[k]] = datacell[j];
      if (k === header.length - 1) {
        Data.push(tempObj);
        console.log(tempObj);
      }
    }
  }
}
console.log(Data);

Whille consoling tempObjs output are as expecting, but when tempObj is pushed to the array the previous elements are overriding by new element.

I was expecting output like

[
  {
    header0: datacel0,
    header1: datacel1,
    header2: datacel2,
    header3: datacel3,
  },
  {
    header0: datacel4,
    header1: datacel5,
    header2: datacel6,
    header3: datacel7,
  }
];

I am getting output like below all the objects are same or overridding

[
  {
    header0: datacel60,
    header1: datacel61,
    header2: datacel62,
    header3: datacel63,
  },
];

Lazy initialization problem with local storage in Next js

I’ve encountered a problem referencing window; the error is described as:

ReferenceError: window is not defined

I’m trying to set a local storage value by using lazy initialization:

const [colors, setColors] = useState(()=>{
  if(window){
    return localStorage.getItem("_appColor") ?
    JSON.parse(localStorage.getItem("_appColor")) : null
  }else {
    return null
  }
});

I tried adding a check for window object in the code above, but I still get the reference error.

I didn’t use useEffect because it causes the color object to be undefined initially and then it will get the data from local storage.

How to use Lazy initialization for useState hook inside of client components to get local storage data without encountering reference error?

Why should we use lazy loading if browser caches the project’s bundle files?

I understand that browser caching can store bundled files for faster retrieval, so once the user has visited the site, subsequent visits should load the cached files rather than downloading them again. However, in this scenario, why is lazy loading still recommended in Angular applications or any single-page applications (SPAs)? Is it necessary if the browser already caches the entire project’s bundle?

I implemented lazy loading in my Angular app and tested it with browser caching enabled. I used Chrome DevTools to monitor the caching behavior.

I expected caching to make lazy loading less necessary, since cached files should load faster, but I wasn’t sure if this would affect initial load time and performance the same way.

JS array subtracting values with next index

I have an array of increasing numbers representing energy meter values, either weekly, monthly, or yearly:

[18240,18290,18340,18400,18470,18510,18600]

Desired output is the difference between the next element e.g.:

[50,50,60,70,40,90]

Here how the data looks like Excel: Example Data:enter image description here

Reloading Ajax Data Table after date change

I’m creating a Booking dashboard on my asp.net MVC project. Here I have given the DateTime selector for the main view and from the script, I’m assigning the current date to the date time picker on the document ready function.

then it passes the current date to ajax via the Ajax data table returns the data assigns it to the table and shows the data.

Here I have added the table on the partial view. The reason I added this table to the partial view is to reload the partial view when if there is any change.

Here is my HTML view code

<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row">
    <div class="col-md-12 col-sm-12 col-xs-12">
      <div class="card mb-4">
        <div class="card-body">
          <div class="date-container">
            <input type="date" id="bookingDate" name="bookingDate" />
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12 col-sm-12 col-xs-12"> 
    @{ Html.RenderPartial("_ArrivingSection"); } </div>
  </div>
  <div class="row">
    <div class="col-md-6 col-sm-6 col-xs-6"> 
    @{ Html.RenderPartial("_InProcessJobsSection"); } </div>
    <div class="col-md-6 col-sm-6 col-xs-6"> 
    @{ Html.RenderPartial("_FutureBookingsSection"); } </div>
  </div>

This is the current working script that get the data from the controller and show on the table.

 $('#arriving').DataTable({
    processing: true,
    serverSide: true,
    filter: true,
    scrollY: '200px', // Set the fixed height for the table
    orderMulti: false,
    ajax: {
       url: '@Url.Action("GetArrivingInformations", "Booking")',
       type: "POST",
       datatype: "json",
    },
    columns: [{
          "data": "CustomerName",
          "name": "Customer Name"
       },
       {
          "data": "ContactNumber",
          "name": "Contact Number"
       },
       {
          "data": "ServiceName",
          "name": "Service"
       },
       {
          "data": "CheckInTime",
          "name": "Check In",
          "render": function (data, type, row) {
             // Assuming data is a TimeSpan object with Hours and Minutes
             if (data) {
                // Convert the TimeSpan to a valid time in Date format
                let hours = data.Hours;
                let minutes = data.Minutes;

                // Create a Date object with the current date but set the time to the TimeSpan's hours and minutes
                let date = new Date();
                date.setHours(hours, minutes);

                // Format the date to AM/PM
                return date.toLocaleTimeString([], {
                   hour: '2-digit',
                   minute: '2-digit',
                   hour12: true
                });
             }
             return 'Invalid Time';
          }
       },
       {
          "data": "EncryID",
          "render": function (data, type, row) {
             // Check if customer has already arrived
             if (row.IsCustomerArrived) {
                // If arrived, don't display the 'Arrived' button
                return `<div class="btn-group bx-pull-right" role="group">
                     <a href="#" class="btn-info btn-sm common-btn" onclick="openAssignJobModal('${data}', '${row.ServiceName}','${row.CustomerName}')">Assign Job</a>&nbsp;&nbsp;

                 </div>`;
             } else {
                // Display the 'Arrived' button if the customer hasn't arrived
                return `<div class="btn-group bx-pull-right" role="group">
                     <a href="#" class="btn-primary btn-sm common-btn" onclick="markAsArrived('${data}', this)">Arrived</a>&nbsp;&nbsp;
                    <a href="#" class="btn-info btn-sm common-btn" onclick="openAssignJobModal('${data}', '${row.ServiceName}')">Assign Job</a>&nbsp;&nbsp;

                 </div>`;
             }
          }
       }
    ],
    language: {
       search: "Search"
    }
 });

I want to do the same when date is changed, then pass the date to the controller and get the data and reload the table

This is what I have tried, but it’s not working, I got so many errors with the data table scripts. When I added the getting data to the document ready function it get errors like datatable is not defined, Datatable is not loaded like wise errors. Can some one help me to complete this process with this way or any alternative way ?

<script src="~/Addons/DataTable/jquery-3.6.1.min.js"></script>
<!-- DataTables -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script>

< script >

    var arrivingTable; // Declare this globally so we can access it from the date change function

$(document).ready(function () {

    // Function to safely reload the table
    function safeReloadTable() {
        arrivingTable.ajax.reload();
    }

    // Bind date change event
    $('#bookingDate').on('change', function () {
        console.log('Date changed:', $(this).val());
        safeReloadTable();
    });
    // Set current date in the date picker
    const today = new Date().toISOString().split('T')[0];
    $('#bookingDate').val(today);

    try {
        arrivingTable = $('#arriving').DataTable({
            processing: true,
            serverSide: true,
            filter: true,
            scrollY: '200px',
            orderMulti: false,
            ajax: {
                url: '@Url.Action("GetArrivingInformations", "Booking")',
                type: "POST",
                datatype: "json",
                data: function (d) {
                    return $.extend({}, d, {
                        "bookingDate": $('#bookingDate').val()
                    });
                }
            },
            columns: [
                // Your existing columns configuration
                {
                    "data": "CustomerName",
                    "name": "Customer Name"
                },
                {
                    "data": "ContactNumber",
                    "name": "Contact Number"
                },
                {
                    "data": "ServiceName",
                    "name": "Service"
                },
                {
                    "data": "CheckInTime",
                    "name": "Check In",
                    "render": function (data, type, row) {
                        if (data) {
                            let hours = data.Hours;
                            let minutes = data.Minutes;
                            let date = new Date();
                            date.setHours(hours, minutes);
                            return date.toLocaleTimeString([], {
                                hour: '2-digit',
                                minute: '2-digit',
                                hour12: true
                            });
                        }
                        return 'Invalid Time';
                    }
                },
                {
                    "data": "EncryID",
                    "render": function (data, type, row) {
                        if (row.IsCustomerArrived) {
                            return `<div class="btn-group bx-pull-right" role="group">
                                <a href="#" class="btn-info btn-sm common-btn" onclick="openAssignJobModal('${data}', '${row.ServiceName}','${row.CustomerName}')">Assign Job</a>
                            </div>`;
                        } else {
                            return `<div class="btn-group bx-pull-right" role="group">
                                <a href="#" class="btn-primary btn-sm common-btn" onclick="markAsArrived('${data}', this)">Arrived</a>
                                <a href="#" class="btn-info btn-sm common-btn" onclick="openAssignJobModal('${data}', '${row.ServiceName}','${row.CustomerName}')">Assign Job</a>
                            </div>`;
                        }
                    }
                }
            ]
        });

    } catch (error) {
        console.error('Error initializing DataTable:', error);
    }
});

</script>

Use Chart.js in a custom wordpress theme

I’m trying to use Chart.js in a custom made wordpress theme. I installed the package according to the step-by-step guide on the website of Chart.js. In my main theme folder I now have the folder node_modules.

In my main.js file I want to add the javascript to setup the graph, but I get an error at the first line in my js file: import Chart from ‘chart.js/auto’;

The error I get says: Mixed Content: The page at ‘https://www.xxxxxxxxxxxxxxxxx.io/’ was loaded over HTTPS, but requested an insecure script ‘http://www.xxxxxxxxxxxxxxx.io/wp-content/themes/xxxxxxxxxxxxxxxxtheme/js/node_modules/chart.js/auto/’. This request has been blocked; the content must be served over HTTPS.

How can I fix this?

Regards,
Sebastiaan

I have entered the code exactly like the instructions of the step-by-step guide.

Ref to html element does not have correct height

I know this has been asked many times and the answer is always that the effect does not run when refs are mutated but that is not the issue because I run the effect every second until I have an html element with height. This is because the element is rendered later and has a height of 0 until user fills our something and clicks a button.

Here is the code I’m using:

const [containerHeight, setContainerHeight] = useState(200);
const [checkCompnent, setCheckComponent] = useState(0);

useEffect(() => {
  let clear = setTimeout(() => {
    console.log(
      'in timeout',
      stickyContainerRef.current,
      stickyContainerRef.current?.clientHeight,//allways logs 0
      stickyContainerRef.current?.id
    );
    if (
      stickyContainerRef.current &&
      stickyContainerRef.current.clientHeight
    ) {
      //never happens
      console.log('setting height', stickyContainerRef.current.clientHeight);
      setContainerHeight(stickyContainerRef.current.clientHeight);
    } else {
      console.log('retry');
      setCheckComponent((c) => c + 1);
    }
  }, 1000);
  return () => {
    clearTimeout(clear);
  };
}, [checkCompnent]);


<div id="whynotworky" ref={stickyContainerRef}>

The effect runs every second but the element never has a height other than 0 the id is correctly logged as whynotworky and when I open the dev console and run document.getElementById("whynotworky").clientHeight it’ll give me 2700. It’s almost like React set the ref but then never updates it on later renders. I’m tempted to ditch the broken ref way and just use document.getElementById but I don’t think you’re supposed to do this.

I’m running this in Firefox and React version is 17.0.2

How can I pink a form? [closed]

How can I send my form to chrome

When I try opening the link on chrome,it is not opening the form,it is only bringing other websites page.so please can you help me in it because I really needed it and it is very urgent because my client has been disturbing me to give him the link and I have been trying the link but it is not working

Using my AWS API with my Wix Velo website

I have an api hosted on AWS’s ECS. I am using Wix as the front end. let response = await fetch(url) works fine until I publish for production. I get the following error:

createConsoleProxy.ts:47 TypeError: Failed to fetch
    at eval (active$wBiEvent.js:56:19)
    at eval (c1dmp.js:48:3)
    at s (react-velo.esm.js:11:12552)
    at Generator.eval [as _invoke] (react-velo.esm.js:11:12552)
    at Generator.eval [as next] (react-velo.esm.js:11:12552)
    at A (react-velo.esm.js:11:12552)
    at i (react-velo.esm.js:11:12552)
    at eval (react-velo.esm.js:11:12552)
    at new Promise (<anonymous>)
    at eval (react-velo.esm.js:11:12552)
(anonymous) @ createConsoleProxy.ts:47
eval @ active$wBiEvent.js:56
eval @ c1dmp.js:68
Promise.catch
eval @ c1dmp.js:48
s @ react-velo.esm.js:11
eval @ react-velo.esm.js:11
eval @ react-velo.esm.js:11
A @ react-velo.esm.js:11
i @ react-velo.esm.js:11
eval @ react-velo.esm.js:11
eval @ react-velo.esm.js:11
r @ c1dmp.js:7
n @ c1dmp.js:7
eval @ c1dmp.js:16
eval @ corvidEvents.js:73
(anonymous) @ registerEvent.ts:51
(anonymous) @ clientWorker.ts:157
n @ comlink.ts:312

My research leads me to believe this is a CORS issue that is resolved by moving my fetch requests to the back end of Wix. When I do that I get his error:

    request to https://App-load-balancer-one-XXXXXXXXXXXXXX.amazonaws.com:XXX/getUser failed, reason: Hostname/IP does not match certificate's altnames: Host: app-load-balancer-one-XXXXXXXXXXXXXX.amazonaws.com. is not in the cert's altnames: DNS:mydomain.com

It seems the load balancer is not recognizing my website anymore. What is the correct way to use my api?

How to fix the “preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header” warning on my express app?

I’m making a second hand bookstore website that uses Aiven as the database and Vercel to deploy. It’s rather simple because it’s a school project, and it uses vanilla JS. I am trying to fetch some data from some APIs but they don’t work at all.

Here’s my server.js

const express = require('express');
const mysql = require('mysql2');
const path = require('path');
const cors = require('cors');
const fs = require('fs');

const fetch = (...args) =>
    import("node-fetch").then(({ default: fetch }) => fetch(...args));

const app = express();
const PORT = process.env.PORT || 3001;

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

const corsOptions = {
    origin: 'http://localhost:3001', // Your frontend origin
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
};

app.use(cors(corsOptions));
require('dotenv').config();

const connection = mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    port: process.env.DB_PORT,
    ssl: {
        rejectUnauthorized: false,
        ca: fs.readFileSync(process.env.SSL_CA),
    },
});

console.log('Connecting to database:', {
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    database: process.env.DB_NAME,
    port: process.env.DB_PORT,
});

connection.connect(err => {
    if (err) {
        console.error('Database connection error:', err);
        return;
    }
    console.log('Connected to the database');
});

app.get('/test-db', (req, res) => {
    connection.query('SELECT 1', (err, results) => {
        if (err) {
            return res.status(500).json({ error: 'Database connection error' });
        }
        res.json({ message: 'Database is connected', results });
    });
});

app.get('/books', (req, res) => {
    const query = 'SELECT * FROM books';

    connection.query(query, (err, results) => {
        if (err) {
            return res.status(500).json({ error: 'Error fetching books' });
        }
        res.json(results);
    });
});


console.log('Database Host:', process.env.DB_HOST);
console.log('Database Name:', process.env.DB_NAME);

connection.connect(err => {
    if (err) {
        console.error('Database connection error:', err);
        return;
    }
    console.log('Connected to the database');
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

console.log('Using SSL CA file:', process.env.SSL_CA);
console.log('Reading CA:', fs.readFileSync(process.env.SSL_CA).toString());

app.use((req, res, next) => {
    console.log(`Incoming Request: ${req.method} ${req.url}`);
    console.log('Request Headers:', req.headers);
    next();
});

and here’s the html file where the books are fetched

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inventory</title>
    <link rel="stylesheet" href="istyle.css">
</head>
<body>
    <div id="navbar">
        <img src="images/BookbackICON.png" alt="">
        <label class="hamburger-menu">
            <input type="checkbox" />
        </label>
        <aside class="sidebar">
            <nav>
                <a href="index.html">Home</a>
                <a href="inventory.html">Inventory</a>
            </nav>
        </aside>
    </div>
    <section id="sec1">
        <span id="search">
            <input type="text" id="search-input" placeholder="Search for a book by name">
            <button id="search-button">Search</button>
        </span>
        <ul id="book-list"></ul>
    </section>

    <script>
        
        let books = [];  
        let uniqueBooks = [];  
        let duplicateCounts = {};

        function deduplicateBooks(data) {
    const uniqueBooksMap = {};
    duplicateCounts = {};

    data.forEach(book => {
        const isbnFull = book.id.split('-')[0]; // Use the full ISBN without trimming the last 5 digits
        const grade = book.grade; // Get the grade

        const uniqueKey = `${isbnFull}-${grade}`;


        if (duplicateCounts[uniqueKey]) {
            duplicateCounts[uniqueKey]++;
        } else {
            duplicateCounts[uniqueKey] = 1;
            uniqueBooksMap[uniqueKey] = book; // Store unique book information
        }
    });


    return Object.values(uniqueBooksMap);
}

function fetchBooks() {
fetch('https://bookback-i1o4juwqu-mohammed-aayan-pathans-projects.vercel.app/books', {
    method: 'GET', // Change as needed
    headers: {
        'Content-Type': 'application/json', // Change as needed
        // Any other headers you might need
    },
    credentials: 'include', // Include this if your API requires credentials
})
.then(response => {
    if (!response.ok) {
        throw new Error('Network response was not ok: ' + response.statusText);
    }
    return response.json();
})
.then(data => {
    console.log('Fetched books:', data);
})
.catch(error => {
    console.error('Fetch error:', error);
});
}


        function displayBooks(booksToDisplay) {
            const bookList = document.getElementById('book-list');
            bookList.innerHTML = ''; // Clear the current list


            const listItems = [];

            booksToDisplay.forEach(book => {
    const isbn = book.id.split('-')[0]; // Extract full ISBN part
    const li = document.createElement('li');
    li.style.cursor = 'pointer'; // Change cursor to pointer for better UX

    fetch(`https://www.googleapis.com/books/v1/volumes?q=isbn:${isbn}`)
        .then(response => response.json())
        .then(bookData => {
            const img = document.createElement('img');
            img.style.borderRadius = '4px';
            const title = book.name || 'Title not available';

            // Handle Google Books data
            if (bookData.items && bookData.items.length > 0) {
                const bookInfo = bookData.items[0].volumeInfo;
                const imageLinks = bookInfo.imageLinks;
                const coverImage = imageLinks?.large || imageLinks?.medium || imageLinks?.thumbnail || 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/No_image_available.svg/1200px-No_image_available.svg.png';
                img.src = coverImage;
            } else {
                img.src = `https://images-na.ssl-images-amazon.com/images/P/${isbn}.L.jpg`;
            }

            img.alt = title;
            img.style.maxWidth = '200px';  // Adjust the image size as needed

            // Handle price safely (fallback if not a number or missing)
            let priceDisplay = 'Price not available';
            if (book.price && !isNaN(book.price)) {
                priceDisplay = `AED ${parseFloat(book.price).toFixed(2)}`;
            }

            // Display the book information, title, image, and stock
            li.appendChild(img);
            li.appendChild(document.createTextNode(title));
            li.appendChild(document.createElement('br'));
            li.appendChild(document.createTextNode(`Grade: ${book.grade}`));
            li.appendChild(document.createElement('br'));
            li.appendChild(document.createTextNode(`${priceDisplay}`));

            // Fix the duplicate count display logic
            const countKey = `${book.id.split('-')[0]}-${book.grade}`;  
            const countDisplay = `No. in stock: ${duplicateCounts[countKey] || 1}`;
            li.appendChild(document.createElement('br'));
            li.appendChild(document.createTextNode(countDisplay));

            const isbnInfo = document.createElement('span');
            isbnInfo.textContent = `ISBN: ${book.id}`;
            isbnInfo.style.display = 'none'; // Hide it initially
            li.appendChild(isbnInfo); // Append the ISBN info to the list item


            li.onclick = (event) => {
                event.stopPropagation(); // Prevent click event from bubbling up to the document


                listItems.forEach(item => {
                    item.style.filter = 'none'; // Remove blur
                    const isbnSpan = item.querySelector('span');
                    if (isbnSpan) {
                        isbnSpan.style.display = 'none'; // Hide ISBN
                    }
                });


                if (isbnInfo.style.display === 'none') {
                    isbnInfo.style.display = 'inline'; // Show ISBN
                    li.style.height = 'auto'; // Expand the clicked item
                    li.style.filter = 'none'; // Remove blur from the clicked item
                } else {
                    isbnInfo.style.display = 'none'; // Hide ISBN
                }


                li.style.filter = 'none'; // Ensure the clicked item is not blurred
                listItems.forEach(item => {
                    if (item !== li) {
                        item.style.filter = 'blur(5px)'; // Blur the other items
                    }
                });
            };

            listItems.push(li); // Add the current item to the listItems array

            bookList.appendChild(li);
        })
        .catch(error => {
            console.error('Error fetching book image from Google:', error);


            const img = document.createElement('img');
            img.src = `https://images-na.ssl-images-amazon.com/images/P/${isbn}.L.jpg`; // Fallback Amazon image
            img.alt = 'No cover image available';
            img.style.maxWidth = '200px';  // Adjust the image size as needed


            let priceDisplay = 'Price not available';
            if (book.price && !isNaN(book.price)) {
                priceDisplay = `AED ${parseFloat(book.price).toFixed(2)}`;
            }

            li.appendChild(img);
            li.appendChild(document.createTextNode(` Title: ${book.name}, ISBN: ${book.id}, Grade: ${book.grade}, ${priceDisplay}`));
            bookList.appendChild(li);
        });
});


            document.addEventListener('click', () => {
                listItems.forEach(item => {
                    item.style.height = '260px'; // Reset height to auto
                    item.style.filter = 'none'; // Remove blur from all items
                    const isbnSpan = item.querySelector('span');
                    if (isbnSpan) {
                        isbnSpan.style.display = 'none'; // Hide ISBN
                    }
                });
            });
        }


        function searchBooks() {
            const searchTerm = document.getElementById('search-input').value.toLowerCase();
            const filteredBooks = uniqueBooks.filter(book => book.name.toLowerCase().includes(searchTerm));
            displayBooks(filteredBooks);
        }


        document.getElementById('search-button').addEventListener('click', searchBooks);


        fetchBooks();
    </script>
</body>`your text`
</html>

I tried doing all sorts of things to mitigate this issue, but this will not budge. If you need anything else, I’ll provide it as promptly as I can.

The errors I get

The products persist in local storage after being removed

    cart.js=
        import {products} from"../html/products.js";


        export const cart=JSON.parse(localStorage.getItem('cart')) ||[
            {}
        ];


        let cartHTML="";
        cart.forEach(x=>{
            cartHTML+=`<div class="product" data-product-id="${x.id}">
            <div class="image">
            <img class="img" src="${x.image}" alt="Product Image">
            </div>
            <div class="content">
                <h2>${x.name}</h2>
                <p>Price:Rs.${x.price} </p>
                <p>Quantity:<p id="quantity">${x.quantity}</p></p>
                <button class="update">update</button><button class="delete">delete</button>

                <br><br>
            </div>
            </div>`
            });
        document.querySelector(".totalHTML").innerHTML=cartHTML;

        export function addToCart(event){
        const ProductId= event.target.closest('.productParent').querySelector('.products').dataset.productId;
        const Product= products.find(product=>product.id===ProductId);

        const dropDownElement = event.target.closest('.content').querySelector('.select');
        let selectedValue = Number(dropDownElement.value);

        const matchingProduct =cart.find(x=>x.id===Product.id)
        if(matchingProduct){
            document.querySelector(`.product[data-product-id="${ProductId}"] #quantity`)+=selectedValue;
        }else if(Product) {
            Product.quantity = selectedValue;
            cart.push(Product);
            console.log("pushed");
        }
        localStorage.setItem('cart', JSON.stringify(cart));
        };

        const deleteBTNs=document.querySelectorAll('.delete');
        deleteBTNs.forEach((x=>{
            x.addEventListener("click", (e)=>{
                const nearProduct =e.target.closest('.product')
                const ProductId= nearProduct.dataset.productId;
                console.log(nearProduct.dataset)
                const updatedCart=cart.filter(x=>x.id !== ProductId)
                console.log(updatedCart)
                // localStorage.setItem("cart", JSON.stringify(updatedCart))
                nearProduct.remove();
                localStorage.setItem("cart", JSON.stringify(updatedCart));
                // console.log(JSON.parse(localStorage.getItem('cart')))
            })}));

    script.js(main script file)
            import {products} from"../html/products.js";
            import {addToCart, toDelete, } from"../html/cart.js";


            let productsHTML="";
            products.forEach(x => {
            productsHTML+=`
                <div class=productParent><div class="products" data-product-id="${x.id}">

                <div class="image">
                    <img class="img"src="${x.image}" alt="">
                </div>
                <div class="content">
                <div class="productName">${x.name}</div>
                <div class="productPrice">Rs.${x.price}</div>
                <select name="number"  class="select" >
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option>
                    <option value="10">10</option>
                </select>
                <button class="addtocart" >Add To Cart</button>
                </div>
            </div>
            </div>`
            });
            document.querySelector(".totalHTML").innerHTML=productsHTML;



            const buttons = document.querySelectorAll('.addtocart');

            buttons.forEach(btn => {
                btn.addEventListener("click", (e) => {

                    addToCart(e);
                    
                    //for cart Quantity 
                    const selectElement = e.target.closest('.content').querySelector('.select');
                    let selectedValue = Number(selectElement.value);
                    cartMath(selectedValue);
                });
            });

            let cartQuantity=0;
            export function cartMath(x){
            cartQuantity+=x;
            document.getElementById("cartQuantity").innerHTML=cartQuantity;
            };

    homepage.html(main html)
            <!DOCTYPE html>
            <html lang="en">
            <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">
                <title>Document</title>
                <link rel="stylesheet" href="/css/homepage.css">
            </head>
            <body>
                <div class="nav"><a href="../html/cartpage.html">Cart</a><span id="cartQuantity">00</span>
                </div>
                    <div class="totalHTML">
                        <!-- html that is now in script.js-->
                    </div>
            </body>

            <script src="script.js" type="module"></script>
            <script src="products.js" type="module"></script>
            <script src="cart.js" type="module"></script>


            </html>

    cartpage.html(cart html)
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <link rel="stylesheet" href="../css/cartstyle.css">
                <title>Add to Cart</title>
            </head>
            <body>
            <div class="totalHTML">
            </div>

            <div class="cart-summary">
                <h2>Cart Summary</h2>
                <p>Total Quantity: <span id="total-quantity">0</span></p>
                <p>Total Sum: Rs. <span id="total-sum">0</span></p>
                <p>Delivery Charge: Rs. 250</p>
                <p>Dashain Offer: Rs. -50</p>
                <h3>Total Payable: Rs. <span id="total-payable">0</span></h3>
                <button class="buynow">Buy Now</button>
            </div>

            </body>
            <script src="cart.js" type="module"></script>
            </html>

    products.js(the storing of items)
        export const products=[
            {
                id:"1",
                name:"shoe",
                image:"images/products/knit-athletic-sneakers-gray.jpg",
                price:1200,
                quantity:1,
            },
            {
                id:"2",
                name:"shirt",
                image:"images/products/adults-plain-cotton-tshirt-2-pack-teal.jpg",
                price:1000,
                quantity:1,
            }, 
            {
                id:"3",
                name:"Sandals",
                image:"images/products/women-beach-sandals.jpg",
                price:200,
                quantity:1,
            },
            {
                id:"4",
                name:"Dinner Plate",
                image:"images/products/6-piece-white-dinner-plate-set.jpg",
                price:2750,
                quantity:1,
            },
        ];

So I tried putting the localStorage here and there but didnt work.
i got a suggestion to rerender but i couldnt do it.
another thing i think would work is after clicking delete update the html in cart.js file itself

(please make the deleted product not appear after deleting and reloading the carthtml page)