Why is my form.submit() still refreshing the page even though I’m using preventDefault? [duplicate]

As the question says, I’m trying to suppress the reloading page behaviour that comes with submitting a form but for some annoying reason it continues to refresh even when setting an event listener to catch the submit and do a preventDefault(). When I press enter on the form manually, preventDefault works fine but when I programatically do form.submit(), I continue to have the page reloaded.

document.addEventListener("DOMContentLoaded", function() {
  const passwordInput = document.getElementById("password");
  const fakePassword = "YourPasswordHere"; // Replace with the desired string

  simulateTyping(passwordInput, fakePassword, 0);
});

document.querySelector('form').addEventListener('submit', function(event) {
  event.preventDefault();
});

function simulateTyping(inputElement, text, index) {

  const passwordForm = document.getElementById("passwordForm");

  if (index < text.length) {
    inputElement.value += text.charAt(index);
    index++;
    setTimeout(function() {
      simulateTyping(inputElement, text, index);
    }, 100); // Adjust the timeout for typing speed
  } else {

    passwordForm.submit();

  }

}
<form id="passwordForm" method="post">
  <input type="password" id="password" name="password" placeholder="Enter your password">
</form>

Excel Online Javascript Api Add Allow Edit Range

I’m having trouble adding an allowed edit range to a worksheet protection object using Excel Javascript API. I keep getting an error Cannot read properties of undefined (reading ‘add’). I believe I’ve added the property with statement

worksheet.load("protection/protected", "protection/allowEditRanges");

but maybe this is wrong?

I’ve referred to the API reference here https://learn.microsoft.com/en-us/javascript/api/excel/excel.alloweditrangecollection?view=excel-js-preview

async function protect(worksheetName) {
await Excel.run(async (context) => {
    worksheet = context.workbook.worksheets.getItem(worksheetName);
    worksheet.load("protection/protected", "protection/allowEditRanges");
    await context.sync();
    //can't add without pausing protection 
    worksheet.protection.unprotect("");
           
    var wholerange = worksheet.getRange();
    wholerange.format.protection.locked = true;                            

    worksheet.protection.allowEditRange.add({title: "Range1", rangeAddress: "A4:G500"});
    worksheet.protection.allowEditRange.add({title: "Range2", rangeAddress: "I4::L500"});        

    worksheet.protection.protect({
        allowFormatCells: true,
        allowAutoFilter: true,
        allowDeleteRows: true,
        allowEditObjects: true,
        //allowFormatColumns: true,
        allowFormatRows: true,
        allowInsertHyperlinks: true,
        allowInsertRows: true,
        allowPivotTables: true,
        allowSort: true
    }, "");

    await context.sync();

});

}

Send image file in FormData node JS ends with error

This is my function in my node JS script:

const uploadFile = async () => {
  const buffer = fs.readFileSync('scripts/pose.png')
  const formData = new FormData()

  formData.append('file', buffer, 'dummyName.png')

  const headers = {
    Authorization: `Bearer ${jwt}`,
    maxBodyLength: Infinity,
    maxContentLength: Infinity,
  }

  const response = await axios.post(
    `${process.env.URL}/v1/files`,
    formData,
    {
      headers
    },
  )

  return response
}

no matter what I’m doing it’s not working… with this code I’m getting an error:
“source.on is not a function”

Can someone help me, I tried literally everything!

TypeError: fontkit.create is not a function => problem faced while I was adopting customfont to my pdf using pdf-lib

I am currently modifying pdf files using javascript libraries and node.
This is my code and I cannot solve thr problem of TypeError: fontkit.create is not a function

This is my code.

const pdfDoc = await PDFDocument.load(existingPdfBytes);
pdfDoc.registerFontkit(fontkit);
const fontUrl =
      'https://storage.googleapis.com/filepath/KaushanScript-Regular.ttf';
    const fontBytes = await fetch(fontUrl).then((res) => res.arrayBuffer());
    pdfDoc.registerFontkit(fontBytes);
const customFont = await pdfDoc.embedFont(fontBytes);

While embedding the font, the problem mentioned above occurs.

This is the built-in method of CustomFontSubsetEmbedder.ts

enter code herestatic async for(
fontkit: Fontkit,
fontData: Uint8Array,
customFontName?: string,
fontFeatures?: TypeFeatures,) {
const font = await fontkit.create(fontData);
return new CustomFontSubsetEmbedder(
  font,
  fontData,
  customFontName,
  fontFeatures,
);}

The problem is occuring in the built-in section where I can’t control.

My @pdf-lib/fontkit version is 1.1.1
(“@pdf-lib/fontkit”: “^1.1.1” on my package.json)

I’ve been trying various ways to fix this but I couldn’t.

Hide/Disable element when scrolling, and as soon as scrolling stop, make it appear again

I am trying to create a div tag to cover an embed tag, and did a little javascript so user can not right click the pdf inside embed tag to download it (I know it is useless, I doing this because my customer requested it). And this is the main part: I want to program the scroll so that everytime user scroll, the div tag mentioned above will disappear, so that user can scroll through the pdf. But as soon as they stop scrolling, it will appear again, to prevent user from right click the pdf.
This is my code so far:

var wheeling;
window.addEventListener('wheel', function (e) {
        if (!wheeling) {
            console.log('start wheeling!');
            document.querySelector("#lesson_pdf").style.display = "none";
        }

        clearTimeout(wheeling);
        wheeling = setTimeout(function() {
            console.log('stop wheeling!');
            document.querySelector("#lesson_pdf").style.display = "block";
            wheeling = undefined;
        }, 300);
    });

My html:

<div>
    <div style="position: relative;">
        //the embed tag I want to cover
        <embed src=" {{ getImageFile($pdf_src) }}" class="tw-w-full tw-h-[500px] pdf-reader-frame" style="position: absolute;">
    </div>
    //The div tag I mentioned
    <div style="position: absolute;
                height: 100%;
                width: 100%;
                display: block;
                z-index: 1;" id="lesson_pdf">
    </div>
</div>

The thing is, it doesn’t work as expected. I sometimes have to scroll a lot of time before be able to scroll through the pdf file. Can somebody help me with this?

MUI Textfield not accepting decimal input

I have a textfield to enter unitPrice

   const [unitPrice, setUnitPrice] = useState(0);
   <TextField
      label="Unit Price"
      variant="outlined"
      margin="normal"
      value={unitPrice.toString()}
      type="number"
      fullWidth
      inputProps={{
        min: "0",
        step: "1.0",
      }}
      onChange={handleUnitPriceChange}
      onBlur={handleLineBlur}
    />

And an onchange function that uses a custom function that handles number input. The purpose of the function is to prevent the user from entering more than two decimal digits.

const handleUnitPriceChange = (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    handleNumberInput(event.target.value, setUnitPrice);
  };
export const handleNumberInput = (
  number: string,
  setValue: React.Dispatch<React.SetStateAction<number>>
) => {
  const parsedValue = parseFloat(number);

  if (!isNaN(parsedValue)) {
    const roundedValue = parseFloat(parsedValue.toFixed(2));
    setValue(roundedValue);
  } else {
    setValue(0);
  }
};

When I input a decimal digit in the textfield(2.22 for example) and try to submit my form, I get

“Please enter a valid value. The two nearest valid values are “2 and 3”

I already tried using inputProps step but it didn’t work.
How can I fix this please?

Google Sign-in authentication can’t enable

I’m trying to confire firebase auth for google signin.but here i got stuck.i dont understand what to do and how.as I have already confired and linked the firebase to my project.i have already downloaded and paste the google services file and also provided the SHA-1 key to the firebase setup.
I’ll be very thankful to you if you help me sort this issue.below is the screeshot of problementer image description here

i tried to configure google signin provider but it show this dialogue box that can’t enable google signin for some appsenter image description here

How to use elapsed time to code a function to manipulate DOM

new software engineering student here. I have a problem i cant seem to get my head around. I am currently making a basic rhythm game like guitar hero using html,css and javascript.

I managed to run a elapsedTime function that starts a timer running the moment u press start. But i am stuck thinking how to code a function that uses that elapsed time and uses integers/floats from an array and drops notes according to that number in the array. Basically comparing the numbers in the array to the current elapsed time and determining if its the proper time to drop the note. Any suggestions or explanations will be greatly appreciated thank you!!
let elapsedTime = 0;

 
// Function to update elapsed time
function updateElapsedTime() {
    const currentTime = new Date().getTime();
    elapsedTime = Math.floor((currentTime - startTime) / 1000);
    document.querySelector('.elapsed_Time').innerText = `Elapsed Time: ${elapsedTime} seconds`;
}

Jquery, HTML, CSS Why does my “Auto” .heat-icon-parent does not inherit the same color as my “heat” and “cool” color?

So recently I tried making a mode function that changes color when I click on different mode there are (“Cool”, “Heat”, “Fan”, “Dry”, “Auto”) and lets say I assigned a color for each of them example: Cool = Blue , Heat = Orange etc.

Based on the exact css, functions and event listener I provide why im facing this problem:

  • The .heat-icon-parent for the word “Auto” does not inherit the same color of .heat-icon-parent for the word “heat”? like if I last click on heat the color is orange i want my auto also to be orange and when i click cool and color is blue i want my auto when click is blue too.

this is my code:

// Variable to store the last clicked mode
    var lastClickedMode = 'cool-mode';

    // Mode Toggle
    $('.heat-icon-parent').click(modeToggle);
    $('.heat-icon-parent#cool-mode').addClass('clicked');
    $('.heat-icon-parent').click(modeColor);

    // Set the fill color based on the 'clicked' class for all SVG paths
    $('.heat-icon-parent svg path').css('fill', function () {
        return $(this).closest('.heat-icon-parent').hasClass('clicked') ? '#ffff' : '#AEAEAE';
    });


function modeToggle() {
    // Check if this element is already clicked
    var isClicked = $(this).hasClass('clicked');

    // Remove 'clicked' class from all elements
    $('.heat-icon-parent#cool-mode, .heat-icon-parent#heat-mode, .heat-icon-parent#fan-mode, .heat-icon-parent#dry-mode, .heat-icon-parent#auto-mode').removeClass('clicked');

    // Set the fill color based on the 'clicked' class for all SVG paths
    $('.heat-icon-parent svg path').css('fill', '#AEAEAE');

    // Toggle the 'clicked' class only if it wasn't already clicked
    if (!isClicked) {
        $(this).addClass('clicked');
        // Update the last clicked mode
        lastClickedMode = $(this).attr('id');
        // Set the fill color for the clicked element
        $(this).find('svg path').css('fill', '#ffff');
    }
}

function modeColor() {
    $('.heat-icon-parent').css('background', '');

    // Get the mode associated with the clicked element
    var mode = $(this).attr('id');

    // Update the background color based on the mode
    switch (mode) {
        case 'cool-mode':
            $('.heat-icon-parent.clicked').css('background', 'linear-gradient(141.67deg, #56aff3, #1c71c8)');
            break;
        case 'heat-mode':
            $('.heat-icon-parent.clicked').css('background', 'linear-gradient(141.67deg, #FF8D5D, #e67e22)');
            break;
        case 'fan-mode':
            $('.heat-icon-parent.clicked').css('background', 'linear-gradient(141.67deg, lime, green');
            break;
        case 'dry-mode':
            $('.heat-icon-parent.clicked').css('background', 'linear-gradient(141.67deg, #00BCB5, teal)');
            break;
        case 'auto-mode':
            // Inherit the color of the last clicked mode for auto-mode
            var lastClickedModeColor = $('.heat-icon-parent.clicked').css('background');
            $('.heat-icon-parent.clicked#auto-mode').css('background', lastClickedModeColor);
            break;
        default:
            // Default background color
            $('.heat-icon-parent.clicked').css('background', 'linear-gradient(141.67deg, #56aff3, #1c71c8)');
            break;
    }
}

CSS

.heat-icon-parent.clicked,
.heat-icon-parent.clicked#auto-mode  {
  border-radius: var(--br-21xl);
  background: inherit;
  background: linear-gradient(141.67deg, #56aff3, #1c71c8);
  box-shadow: 0 2px 2.1px rgba(0, 0, 0, 0.4),
  -1px -1px 2px rgba(0, 0, 0, 0.5) inset,
  1px 1px 2px rgba(255, 255, 255, 0.64) inset;
  display: flex;
  flex-direction: row;
  color: var(--white);
}

Getting issue when converting string date format(dd.mm.yyyy, hh:mm) to Date type in Type script

I have a string variable with different date time formats and when converting to the Date type I am getting NaN. from the TypeScript, not using any npm packages how to convert it properly

My Code
Date time format: Deutsch

var stringDeutschdate = "22.02.2022, 15:56" //Deutsch
var stringDeutschdate = "22.02.2022 15:56" //Dansk

I want to convert this to string type to Date type, with the above format

Below is the code

private getUtcDate(defaultDate : Date):Date {
   const now: Date = new Date(defaultDate);
   const formattedDate:string | undefined = this.locale.date.format(
      now,"yyyyMMddHHmm","UTC");
    if(formattedDate === undefined) {
        throw new Error("failed to format date");
    }
    const parsedDate: Date = new Date(formattedDate);
    return parsedDate;
}

Trying to bind in class on a click event but gets an error of “ref is not defined”

Hello everyone I’m trying to bind a click event on a button to toggle a class on vue but I’m kinda stuck on the following code, can you help me with some tips and examples

my structure

dashboard.vue
|_Sidebar.vue  Sidebar Component 
|_Mainpage     
|_SidebarJs // this is where all my function should be called by sidebar component

My Dashboard code

<template>
<Head title="Dashboard" />
<SideBar />
  <!-- start: Main -->
  <main class="w-full md:w-[calc(100%-256px)] md:ml-64 bg-gray-50 min-h-screen transition-all main">
    <div class="py-2 px-6 bg-white flex items-center shadow-md shadow-black/5 sticky top-0 left-0 z-30">
        <button type="button" class="text-lg text-gray-600 sidebar-toggle" @click="SidebarJs.ToggleMenu">
            <i class="ri-menu-line" ></i>
        </button>
    </div>

    <!-- Some very long line of codes for other sections of dashboard  -->
  </main>

Sidebar.vue code

<template>
<div
    :class="[`${isexpanded?'active':''}`]"
    class="fixed left-0 top-0 w-64 h-full bg-gray-900 p-4 z-50 sidebar-menu transition-transform">   
</div>
 <!-- Some very long line of codes for other sections of Sidebar  -->

Sidebar.js

   const isexpanded = ref(false)
    var FunctionScripts = {
    ToggleMenu () {
            isexpanded = ref(false)
            isexpanded.value = !isexpanded.value
            console.log('test')       
    },
    foo () {
        const activeClass = ref('active')
        const errorClass = ref('text-danger')
        console.log('foo')
    },
    bar () { console.log('bar') }
  }
  export default FunctionScripts

import scripts

import { Head } from '@inertiajs/vue3';
import SideBar from '../Components/Sidebar.vue';
import SidebarJs from '@/../../resources/js/Functions/Sidebar';
import {ref} from 'vue';

my references for the codes i learn are from youtube and docs
https://vuejs.org/guide/essentials/class-and-style.html#class-and-style-bindings

my older code works only if all of the codes are not split up or inside a single vue but i want it to be organize so thats why i cant use these codes anymore

old code

<script setup>
import {ref} from 'vue';
const isexpanded = ref(false)
const ToggleMenu = ()=> {
    isexpanded.value = !isexpanded.value
}
</script>

changing Tone.js sequencer events dynamically

I want to change the Sequencer Object’s events array while it is playing.
The following code is from Tone.js Sequencer Page.

const synth = new Tone.Synth().toDestination()
const seq = new Tone.Sequence((time, note) => {
    synth.triggerAttackRelease(note, .1, time)
}, sequence /*I wanna change this arr*/).start(0)

I am a bit lost, to be honest. In the seq Object, there is a property called

Tone.Sequencer._events

And underneath the _events there are handlers that called get and set, but when I checked the source

private _createSequence(array: any[]): any[] {
        return new Proxy(array, {
            get: (target: any[], property: PropertyKey): any => {
                // property is index in this case
                return target[property];
            },
            set: (target: any[], property: PropertyKey, value: any): boolean => {
                if (isString(property) && isFinite(parseInt(property, 10))) {
                    if (isArray(value)) {
                        target[property] = this._createSequence(value);
                    } else {
                        target[property] = value;
                    }
                } else {
                    target[property] = value;
                }
                this._eventsUpdated();
                // return true to accept the changes
                return true;
            },
        });
    }

And I decided, I could use a little help at this point. Is there any way to change/replace the array that is playing without stopping the Tone.Transport?

Tools for Code Evaluation on a Web-Based Programming Exercise Platform

I have been assigned a school project to create a web platform for programming exercises, similar to HackerRank. The idea is for users to input their code and the platform to evaluate whether the output matches the expected results. I am considering using Docker for this purpose. Has anyone implemented something similar and could recommend tools or share their experiences? Any advice would be greatly appreciated. Thank you.

that the output of the code execution matches the expected output

Popup form not coming up after clicking the button [closed]

Please I need your assistance here, I created packages that required a customer to click the button to select or input the amount.

But when click, the popup window will become faded or gray without displaying the form visible enough to input or select data.

Attached image is the problem enter image description hereI’m facing after trying different options. I’m using WordPress.

Or check this link and click on any button under each package: https://salesmancapital.com/investment-package/

Script to Rename the key of a JS object property

The following denotes a simple/basic script to rename the key of an object’s property:

const obj = { firstName: 'Sling', lastName: 'Academy' }; 
obj.name = obj.firstName; // create a new property with the same value
delete obj.firstName; //delete the old property

While the above script may work fine for the JS object provided, it fails to work for a JS object of the type provided below:

const obj = {firstName:{address:'' '',city:'' '', state:'' '', zip:'' '', phone:'' ''},
secondName:{address:'' '',city:'' '', state:'' '', zip:'' '', phone:'' ''},
thirdName: {address:'' '',city:'' '', state:'' '', zip:'' '', phone:'' ''},
.
.
.
}}

As such, I am curious to know what changes need to be made to the script to rename a key or keys for a JS object of the type shown above to rename firstName, secondName, thirdName, …..

created a script to rename a key for a JS object property with nested property/values and it failed to rename the old key with the new one provided as intended.