I made a JavaScript daily trigger for a function that updates an innerHTML and it didn’t run properly

function triggerDailyUpdate() {
        console.log('the Function worked');
        setInterval(function(){
            const now = new Date();
            if (now.getHours() === 0 && now.getMinutes() === 0) {
                console.log("Conditions detected, regenerating table for the next day");
                predictionsContainer.innerHTML = "";
                setupPredictions();
            }
        }, 60000); 

I made a javascript function where it’ll trigger a daily update to a table using an inner HTML. When I checked it on the dev mode from my browser it only run the console.log for “The Function Worked” and the rest of the code didn’t properly run. I tried to test it by changing the get hours and minutes value and it still didn’t trigger. What went wrong? I just wanted it to trigger the setupPrediction function daily based on the getHours and getMinutes value (which is midnight)

How Can i get the productId from the JS function?

<%  
   int productId=?
   ProductsDao pd = new ProductsDao(ConnectionProvider.getConnection());
   Products p=pd.getProductByPid(productId);
%>   
function attachEditEventListeners() {
  const editButtons = document.querySelectorAll('.btn.btn-primary');

  editButtons.forEach(function(button) {
    button.addEventListener('click', function(e) {
      e.preventDefault();
      const modal = document.querySelector('#editModal');
      const productId = button.getAttribute('value');



      button.setAttribute('data-toggle', 'modal');
      button.setAttribute('data-target', '#editModal');

    });
  });
}

I was attempting to retrieve the product information using the product ID when clicking the edit button in order to edit it.

Chrome Extension (v3) – Download a Uint8array file (.ts file) [duplicate]

I have a Uint8array (that I’ve created by concatenating arrayBuffers from fetching several .ts files); I am attempting to send the U8A as a message to a content script in a tab and download it by creating a virtual A element with a filename/url (URL.createObjectURL method and download=”filename.extension”). However, even this is not working; any suggestions?

I’ve tried downloading using chrome.downloads.download({url,filename});
(with a url of arrayBuffer/uint8array/blob)
URL.createObjectURL cannot be used in a serviceWorker FYI.
and sending the uint8array to a CS as a message is also unsuccessful (for unknown reasons).
I’ve also tried converting the uint8array to base64, however this method crashed the browser (the file(s) are 1gb min to 3gb max).

Navigate different cards to their respective page

I am trying to navigate different cards to their respective pages using react-router and use-Navigate but can’t ,as the onclick functionality is not working.

    import React from 'react';
import { Link  , useNavigate} from 'react-router-dom';

const Card = ({ id, imageSrc, title, text }) => (
  <Link to={`/card/${id}`} className="card-link">
    <div className="rounded-lg overflow-hidden shadow-lg hover:shadow-xl transition duration-300">
      <img src={imageSrc} alt="Card" className="w-full h-auto" />
      <div className="p-4">
        <h3 className="text-xl font-semibold mb-2">{title}</h3>
        <p className="text-gray-700">{text}</p>
      </div>
    </div>
  </Link>
);

const Action = () => {
  const cardsData = [
    { id: 1, imageSrc: '/images/tokyo_ghoul.jpg', title: 'Title 1', text: 'The story follows Ken Kaneki, a student who barely survives a deadly encounter with Rize Kamishiro,his date who reveals herself as a ghoul and tries to eat him. He is taken to the hospital in critical condition. ' },
    { id: 2, imageSrc: '/images/tomodachi.jpg', title: 'Title 2', text: 'High school student Yuuichi Katagiri cherishes his close circle of friends, composed of four classmates: Yutori Kokorogi,Shiho Sawaragi, Makoto Shibe, and Tenji Mikasa. However, when the funds for the upcoming school trip are stolen, the incident causes Shiho and Makoto—who had been tasked with collecting the money—to distance ' },
    { id: 3, imageSrc: '/images/Demon_Slayer.jpg', title: 'Title 3', text: "Ever since the death of his father, the burden of supporting the family has fallen upon Tanjirou Kamado's shoulders.Though living impoverished on a remote mountain, the Kamado family are able to enjoy a relatively peaceful and happy life.One day, Tanjirou decides to go down to the local village to make a" },
    { id: 4, imageSrc: '/images/onepiece2.jpg', title: 'Title 4', text: "A fleet of pirate ships with the same Jolly Roger are shown along with a man sporting said flag, Woonan.Next a night scene where piles of gold treasure are seen bright at sea with a silhouette of Woonan.  Then an island is shown while gold rains down as it fades out ending with a shot of a treasure map." },
    { id: 5, imageSrc: '/images/horimiya-img.jpg', title: 'Title 5', text: 'Admired at school for her friendly attitude and academic achievements, high school student Kyouko Hori has been hiding another side of herself.With her parents often away from home due to work, Hori also has to look after her younger brother and do the housework, leaving no opportunities .' },
    { id: 6, imageSrc: '/images/eminence.jpeg', title: 'Title 6', text: "Even in his past life, Cid's dream wasn't to become a protagonist or a final boss.He'd rather lie low as a minor character until it's prime time to reveal he's a mastermind...or at least, do the next best thing-pretend to be one! And now that he's been reborn into another world, he's ready to set the perfect conditions  to live out his dreams to the fullest." },
    // Add more card data as needed
  ];

  const navigate = useNavigate();

  const navigateToCardDetails = (id) => {
    // Navigate to the card details page based on the ID
    switch (id) {
      case 1:
        navigate(`/card/${id}`);
        break;
      // cases for other IDs...
      default:
        break;
    }
  };

  return (
    <div className="grid grid-cols-1 mt-[616px] sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 p-6">
      {cardsData.map(card => (
        <div key={card.id} onClick={() => navigateToCardDetails(card.id)}>
          <Card id={card.id} imageSrc={card.imageSrc} title={card.title} text={card.text} />
        </div>
      ))}
    </div>
  );
};

export default Action;

In the Action component, I’m trying to navigate to different pages when clicking on each card using React Router’s use-Navigate hook. However, the navigation doesn’t seem to work as expected.

Why doesn’t my second OnClick Isloading value work in the RTK Query mutation query?

Why doesn’t my second OnClick Isloading value work in the RTK Query mutation query? When you do onClick for the first time, Isloading is true, but on the second click, it is not, and on the second one, the value remains false

 const [
    getDriverLicenseByPin,
    { data, isLoading },
  ] = useLazyGetDriverLicenseByPinQuery();
  
  const personDataSend = (values) => {
    getDriverLicenseByPin({
      pin: values.Pin,
      driverLicenseNumber: values.DriverLicenseNumber,
    });
  };

How to create animation cards translate

The problem is that I have to create animation translation cards like in this website https://www.chrls.design/
Do you have any suggestions?

I prefer to use pure js, but JQuery is also good

function disableScroll() {
    document.querySelector("html").setAttribute("style", "overflow-y: hidden");
  }
  function enableScroll() {
    document.querySelector("html").setAttribute("style", "overflow-y: auto");
  }

  function disableCardsScrollHack(withDisable) {
    if (withDisable) {
      advantageCard1.addEventListener(
        "animationstart",
        function () {
          disableScroll();
        },
        false
      );
      advantageCard1.addEventListener(
        "animationend",
        function () {
          enableScroll();
        },
        false
      );
      advantageCard2.addEventListener(
        "animationstart",
        function () {
          disableScroll();
        },
        false
      );
      advantageCard2.addEventListener(
        "animationend",
        function () {
          enableScroll();
        },
        false
      );
      advantageCard3.addEventListener(
        "animationstart",
        function () {
          disableScroll();
        },
        false
      );
      advantageCard3.addEventListener(
        "animationend",
        function () {
          enableScroll();
        },
        false
      );
    }
  }

  function slideCards(direction) {
    let proportion = stackArea.getBoundingClientRect().top / window.innerHeight;
    if (proportion <= 0.5) {
      let n = sliderCards.length;
      let index = ((proportion * n) / 2).toFixed(1);
      if (index <= 1 && index > 0.6) {
        if (direction === "UP") {
          advantageCard1.classList.remove("active-down");
          advantageCard1.classList.add("active-up");
        } else {
          advantageCard1.classList.remove("active-up");
          advantageCard1.classList.add("active-down");
        }
        disableCardsScrollHack(true);
      }
      if (index <= 0.6 && index > 0.2) {
        if (direction === "UP") {
          advantageCard2.classList.remove("active-down");
          advantageCard2.classList.add("active-up");
        } else {
          advantageCard2.classList.remove("active-up");
          advantageCard2.classList.add("active-down");
        }

        disableCardsScrollHack(true);
      }
      if (index == 0.2) {
        if (direction === "UP") {
          advantageCard3.classList.remove("active-down");
          advantageCard3.classList.add("active-up");
        } else {
          advantageCard3.classList.remove("active-up");
          advantageCard3.classList.add("active-down");
        }

        disableCardsScrollHack(true);
      }
      if (index < 0.2) {
        if (direction === "UP") {
          advantageCard1.classList.add("active-down");
          advantageCard2.classList.add("active-down");
          advantageCard3.classList.add("active-down");
          disableCardsScrollHack(false);
        }
      }
    }
  }

  function windowScroll() {
    if (this.oldScroll < this.scrollY) {
      slideCards("BOTTOM");
    } else {
      slideCards("UP");
    }
  }

  window.onscroll = function (e) {
    windowScroll();
    this.oldScroll = this.scrollY;
  };

I wrote some bullshit using disable scroll and add some animation, but I need more suitable code)
I saw that in this (https://www.chrls.design/) website they use three js library, maybe you have any examples with using this one

Problems to update and delete an object nested within an array

I am trying to delete one of the objects that are inside the folders folder, I am a beginner in Mongo and I am not very sure how to implement it, I tried the following code and it is ok but the object continues to appear.

This is the object:

{
    _id: ObjectId('6631499d751293d1ac1e7f45'),
    label: 'Test Template',
    folders: [
      {
        fld_name: 'Test Folder One',
        formfield: [],
        _id: ObjectId('663174af751293d1ac1e7f49')
      },
      {
        fld_name: 'Test Folder Two',
        formfield: [],
        _id: ObjectId('663174c7751293d1ac1e7f4c')
      },
      {
        fld_name: 'Test Folder Three',
        formfield: [],
        _id: ObjectId('66317504751293d1ac1e7f4f')
      }
    ],
    createdAt: ISODate('2024-04-30T19:42:21.751Z'),
    updatedAt: ISODate('2024-05-01T06:13:06.192Z')
  }

I want to delete an object that is inside the folders array

I want to delete an object that is inside the folders array. but when I implement the code it tells me ok but it does not eliminate it

export const deleteFolder = async (req: Request, res: Response) => {
  try {
    const query = { _id: req.params.id };
    const deleteFolder = { $pull: { "folders.$[].formfield": { _id: query } } };
    const result = await Template.updateOne(query, deleteFolder);
    console.log(result);
    res.status(201).json({ message: "Folder was deleted successfully!" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ success: false, error: "Something went Wrong!" });
  }
};

How to deep secure the script/code files and monetization of chrome extension

I am done in my extension, and too out of nowhere how what steps or strategies to secure this extension from hackers, as I watched, they can manipulate the code of it.

So may I ask tips and tricks how to deep secure this? Afraid of wrong distributing of this by people.

Thank you very much, you all can be suggest any, am not the only one to be helped here, new creators here may know and be aware of it too, so lets talk about it!

For script security the GPT said, it can be minify script, split script, obfuscated, etc.

For monetization, I dont know how extension creators done this, how they integrate their eg. Paypal etc. with fully secured, and I saw https://github.com/glench/ExtPay for shortcut code for monetization, but it is worth it to just embed it in my extension? since I saw (hacking the extension video) https://www.youtube.com/watch?v=N13a4mov3QQ&t=634s i think i need to be more careful in my moves for other’s counteracts

PHP not playing audio onclick

I’m trying to make a progress bar that when it reaches 100% a sound will produce letting the user know that it’s done.

Here’s my JS:

const progress = document.querySelector(".progressStatus");

let finalValue = 100;
let max = 100;
function changeWidth()
{
    // If it looks overly complicated I'm only at stage 1 I will use this formula more in the future 
    // but it works.
    progress.style.width = `${(finalValue / max) * 100}%`;
    progAudio();
}
function progAudio()
{
    const progAudio = new Audio();
    progAudio.src = "./audios/MONLU.mp3";

    // I've tried singling out the audio
    // didn't work
    // progAudio.play();

    setInterval(function () {
        progAudio.play();
    }, 1000);
    
}

and here’s my PHP:

 echo 
            '
            <button type="submit" class="" name="submit">
                <a href="./phps/taskDone.php? doneid='.$taskId.'" onclick=progAudio(this wouldn't work);           changeWidth(but this func does)">
                    Done
                </a>
            </button><br>';

I am also trying to pass data to my database that’s why it’s in PHP and the JS is just for design.
What confuses me is that the “changeWidth()”, the function that makes the progress bar load, works but the progAudio, the one that holds audio onclick, doesn’t. Both are JS but one doesn’t work.

I’ve tried just putting the progAudio() on the onclick but it doesn’t produce the audio.

I also tried putting them both in a single function

function progUp()
{
    changeWidth();
    progAudio();
}

and still didn’t work.

I researched and apparently php aren’t supposed to output audio but something tells me I’m just not making the PHP and the JS communicate properly.

Is there a way to do this? Ajax or through URL? Google wouldn’t tell me anything.

Thanks in advance!

Success Message Not Showing After One Time

I’m trying to show a message when a new record is added. The first time I add a record, the message appears. But if I add another record, the message doesn’t show up, even though the record is added correctly.

This is my HTML Code

<button id="add">Add Name To Table</button>
<input type="text" placeholder="Enter Name" id="name" style="display: none;">
<input type="text" placeholder="Enter Class" id="class" style="display: none;">

<button id="save" style="display: none;">Add Name</button>
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Class</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<span id="message"></span>
<div id="editdiv"></div>

This is my jquery code

 $(document).ready(function () {

        var value;
        var Nclass;

        $('#add').click(function () {

            $('#name').show();
            $('#class').show();
            $('#save').show();
        });
        $('#save').click(function () {
            if ($('#name').val().length != "" && $('#class').val().length != "") {
                value = $('#name').val().trim();
                Nclass = $('#class').val().trim();

                if (value != "") {
                    var cell = $('<td>').text(value);
                    var classval = $('<td>').text(Nclass);
                    var deletebtn = $('<button>').text('Delete').attr('class', 'delete');
                    var editbtn = $('<button>').text('Edit').attr('class', 'edit');
                    var row = $('<tr>').append(cell, classval, deletebtn, editbtn);
                    $('tbody').append(row);
                    row.hide().fadeIn();
                    $('#message').text("Data Added Successfully").css("color", "green");
                    setTimeout(function () {
                        $('#message').fadeOut();
                    }, 2000);
                    $('#name').val('');
                    $('#class').val('');

                }
            } else {
                $('#message').text("You Cannot Submit While Input Fields Are Empty").css('color', 'red');
                setTimeout(function () {
                    $('#message').fadeOut();
                }, 2000);
            }
        });

    });

React state variable throws error when updated using ++ prefix

I’m Fairly new to React and JS, just exploring the nitty-gritties of the lang.

I’m trying to compare the difference in updating the state variable “counter”, using the ++ operator( and by idiomatic way of counter + 1).

The error I get for the following snippet is:

function App() {
  const [counter, setCounter] = useState(0);

  const incrementCounter = () => {
    setCounter(++counter);
  };

  console.log(counter);

return (
    <>
  <button onClick={incrementCounter}>Increase </button>
    </>
App.jsx?t=1714542208954:31 Uncaught TypeError: Assignment to constant variable.
    at incrementCounter (App.jsx?t=1714542208954:31:18)
    at HTMLUnknownElement.callCallback2 (react-dom_client.js?v=38cf15c3:3672:22)
    at Object.invokeGuardedCallbackDev (react-dom_client.js?v=38cf15c3:3697:24)
    at invokeGuardedCallback (react-dom_client.js?v=38cf15c3:3731:39)
    at invokeGuardedCallbackAndCatchFirstError (react-dom_client.js?v=38cf15c3:3734:33)
    at executeDispatch (react-dom_client.js?v=38cf15c3:7014:11)
    at processDispatchQueueItemsInOrder (react-dom_client.js?v=38cf15c3:7034:15)
    at processDispatchQueue (react-dom_client.js?v=38cf15c3:7043:13)
    at dispatchEventsForPlugins (react-dom_client.js?v=38cf15c3:7051:11)
    at react-dom_client.js?v=38cf15c3:7175:20

Note: I get the error after I click on Increase button

When I try to call the setState function( setCounter ) using counter + 1 the error disappears, I cant wrap my head around the cause.

I get that pre/post fix operators are not suitable for updating react state by I wonder why is the case.

Any insights would be greatly appreciated.

I have a problem while fetching brawl stars api can anyone help me [duplicate]

it shows this error Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
127.0.0.1/:1 Access to fetch at ‘https://api.brawlstars.com/v1/players/%232QQV0G9Q2’ from origin ‘http://127.0.0.1:5500’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

        const playerurl = 'https://api.brawlstars.com/v1/players/<player id>';

const getJSON = async url => {
    try {
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                Accept: 'application/json'`your text`,
                Authorization: 'Bearer <token>',
            },
        });
        if(!response.ok) {throw new Error(response.statusText);}
        const data = await response.json();
        return data;
    }
    catch(error) {
        return error;
    }`your text`
};

getJSON(playerurl).then(data => {
    console.log(data);
}).catch(error => {
    console.error(error);
});`your text`

Prototype chain of function and object result to same Object value but give false when comapared [closed]

I am looking for to check prototype chain of Function and Object. And they refer to the same object value in javascript but gives false when compared.

function cat() {}
let kitty = new cat()

let myObj = {}

console.log(kitty.__proto__.__proto__); // same Object
console.log(myObj.__proto__); // same Object
console.log(Object.prototype); // same Object
// {
//   constructor:ƒ Object(")
//   hasOwnProperty:ƒ hasOwnProperty()
//   isPrototypeOf:ƒ isPrototypeOf()
//   propertyIsEnumerable:ƒ propertyIsEnumerable()
//   toLocaleString:ƒ toLocaleString()
//   toString:ƒ toString()
//   valueOf:ƒ valueOf()
//   __defineGetter__:ƒ __defineGetter__()
//   __defineSetter__:ƒ __defineSetter__()
//   __lookupGetter__:ƒ __lookupGetter__()
//   __lookupSetter__:ƒ __lookupSetter__()
//   __proto__:(...)
//   get __proto__:ƒ __proto__()
// }

// also they are comparable and true when comapre two of them
console.log( kitty.__proto__.__proto__ === Object.prototype); // true
console.log( myObj.__proto__ === Object.prototype); // true 
console.log( myObj.__proto__ === kitty.__proto__.__proto__); // true

// but gives false when compare all three of them even them value is  same
console.log( kitty.__proto__.__proto__ === myObj.__proto__ === Object.prototype); // false