Image Map/If Else statements not fetching correctly

I’m currently writing a little web based point-and-click adventure, when I call to load in the 4th room (function alley4) by clicking the coresponding map in the previous room, it should check for an item in the localstorage and change the image map based on if you have the item or not, allowing for different interactions, this has worked in the past with other rooms but for some reason this one always loads the “localStorage.getItem(“radio”) == 2″ if statement (which should only trigger after placing the item), so it ends up thanking the player for their help before they’ve done anything, even if localstorage is completely clear of all items. For the life of me I cannot figure out why this is happening, by my eye this code should give the player the option to place the item before the character thanks them.

thank you for taking the time to read through my awfully written code <3

(Hopefully I included enough of my code to be useful, if theres any questions or requests for additional context code, don’t hesitate to ask. I included Alley2 html for context, as it triggers alley4() but it shouldn’t be relevent to issue)

        
        /*Get eyeR*/
        function alley4() {
            audio = document.getElementById('walk'),
            audio.volume = 0.7;
            audio.play();
            if (localStorage.getItem("radio") == 1) {
                event.preventDefault();
                audio.addEventListener('ended', function(){
                    let image = document.getElementById("party");
                image.src ="/pics/alley4.png"
                party.useMap = "#placeradio";
                document.getElementById("alley4btn")
                    .style.display = "none";
                    document.body.removeChild(alley2box);
                    document.title = "...";
                    audio = document.getElementById('convo');
                    document.getElementById("convo").loop = true; 
                    audio.play();
                })
        } 
        
        
        else if (localStorage.getItem("radio") == 2){
            event.preventDefault();
            audio.addEventListener('ended', function(){
                let image = document.getElementById("party");
            image.src ="/pics/alley4radio.png"
            party.useMap = "#partymap";
            document.getElementById("alley4btn")
                .style.display = "none";
                document.body.removeChild(alley2box);
                document.title = "...";
                audio = document.getElementById('convo');
                document.getElementById("convo").loop = true; 
                audio.play();
                snd = document.getElementById('radio');
                snd.play();
            })
        }

        else {
            event.preventDefault();
            audio.addEventListener('ended', function(){
                let image = document.getElementById("party");
            image.src ="/pics/alley4.png"
            party.useMap = "#noradio";
            document.getElementById("alley4btn")
                .style.display = "none";
                document.body.removeChild(alley2box);
                document.title = "...";
                audio = document.getElementById('convo');
                document.getElementById("convo").loop = true; 
                audio.play();
            })
        }
           
        }
        
        
        /*Place Radio*/
                function placeradio() {
            let image = document.getElementById("party");
            image.src ="/pics/alley4radio.png"
            party.useMap = "#radiothanks";
            document.getElementById("placeradiobtn")
            localStorage.setItem("radio", "2");
            audio = document.getElementById('convo');
            audio.pause();
            snd = document.getElementById('radio');
            snd.play();
        }
<!--Alley 2-->

<div id="alley2box">
<img id="alley2" src="" usemap="#alley2" class="center">
<map name="alley2">
    <area id="shop1btn" class="cursor-click" onclick="shop1()" coords="333,288,673,536" shape="rect">
    <area id="alley3btn" class="cursor-click" onclick="alley3()" coords="0,0,84,669" shape="rect">
    <area id="alley4btn" class="cursor-click" onclick="alley4()" coords="1005,1,921,669" shape="rect">
</map>
</div>

<!--Alley 4-->

<div id="partybox">
  <img id="party" src="" usemap="" class="center">
  
    <map name="noradio">
       <area id="boring" class="cursor-click" coords="625,329,747,502" shape="rect">
    </map>

    <map name="placeradio">
       <area id="placeradiobtn" class="cursor-click" onclick="placeradio()" coords="433,455,726,608" shape="rect">
    </map>

    <map name="radiothanks">
        <area id="thanks" class="cursor-click" coords="625,329,747,502" shape="rect">
    </map>

    <map name="partymap">
        <area id="party" class="cursor-click" coords="654,336,718,397" shape="rect">
        <area id="radiobtn" class="cursor-click" coords="416,397,696,567" shape="rect">
    </map>
    
</div>

I’ve tried everything short of rewritting the logic for this room, i’ve tried tinkering with function and localstorage names, shifting around the order of the if statements, along with other attempts im not remembering rn, but nothing.

next.js disable nested layouts for a single route [duplicate]

I am starting my first Next.JS project. I understand that it uses the folder layout to determine different routes, such as if I have a “settings” folder containing a page.js file, and I go to the /settings route on my hosted site, I would see the settings/page.js file.

I also understand that a layout.js file with appear to wrap around the page.js file when you specify how it displays a {children} element.

My project has a structure like so:
https://github.com/MartinBarker/next.js-demo.git

app
├───api
├───dashboard
│   ├───download
│   └───settings
├───favicon.ico
├───globals.css
├───layout.js
├───page.js
└───rendertune
    ├───layout.js
    └───page.js

When I visit my homepage route “/” I see my app/layout.js and app/page,js perfectly fine, looks good and works as expected:

enter image description here

For my /rendertune route, I want only the rendertune/layout.js to be applied, I do not want the root app/layout.js file to be applied for this route and only this route, but if I visit my /rendertune local route, I can see both the app/layout.js and app/rendertune/layout.js being applied, and the app/rendertune/layout.js is being cutoff too:

enter image description here

How do I make it so my /rendertune route only uses the rendertune/layout.js file and does not use the root layout.js file? I have tired grouping folders and following the next.js routing guide but nothing has worked so far.

next.js disable avoid nested layouts for a single route [duplicate]

I am starting my first Next.JS project. I understand that it uses the folder layout to determine different routes, such as if I have a “settings” folder containing a page.js file, and I go to the /settings route on my hosted site, I would see the settings/page.js file.

I also understand that a layout.js file with appear to wrap around the page.js file when you specify how it displays a {children} element.

My project has a structure like so:
https://github.com/MartinBarker/next.js-demo.git

app
├───api
├───dashboard
│   ├───download
│   └───settings
├───favicon.ico
├───globals.css
├───layout.js
├───page.js
└───rendertune
    ├───layout.js
    └───page.js

When I visit my homepage route “/” I see my app/layout.js and app/page,js perfectly fine, looks good and works as expected:

enter image description here

For my /rendertune route, I want only the rendertune/layout.js to be applied, I do not want the root app/layout.js file to be applied for this route and only this route, but if I visit my /rendertune local route, I can see both the app/layout.js and app/rendertune/layout.js being applied, and the app/rendertune/layout.js is being cutoff too:

enter image description here

How do I make it so my /rendertune route only uses the rendertune/layout.js file and does not use the root layout.js file? I have tired grouping folders and following the next.js routing guide but nothing has worked so far.

Unable to display moal in UI automation test in testcafe even though the same steps work manually

I am having an issue displaying a modal in my testcafe automation test unless I refresh the browser when I am on the page. I will explain the situation.

What I am trying to replicate is that if I log into a device using an API call, when I then log into an application via the UI, a modal will appear stating I am logged in as either role A or role B which was selected on the API call.

Now manually this works where I login via API and then login UI and see the modal. But when I try to do the same via automation, the modal doesn’t appear after UI login, unless I refresh the page and it then appears by doing this:

await t.eval(() => location.reload());

However, I cannot write a test where I log into the UI and there is no modal, then refresh the page and modal appears as that’s not valid. Instead what I was hoping is that if I refresh the UI page before UI login and then I log in, then I was hoping to see the modal but this does not happen.

I have also tried the following before UI login:

await t.navigateTo(config.ui.loginUrl); //navigate to page again to try to refresh

await t.eval(() => window.dispatchEvent(new Event('authStateChanged'))) //trigger event call

await wait (5000) //tried to wait between API login and UI login and included these waits after the above two methods as well

When I console log the innerHTML, the modal html code is just not existent, unless I refresh the page after the login. It’s weird. What else can I try between the API and UI login to try and get the UI page to work and show the modal after login?

Code:

    ['ROLE A', 'ROLE B'].forEach((account: string) => {
  test.only(`Validate application auto login with selected "${account}" role after role login in device`, async (t) => {
    //create device below and use the device properties to perform api login
    sessionCreated = true;
    const device = await createDevice({
      venueId: '888001',
      accountType: account as ACCOUNT_TYPE,
      requireLogin: false,
      deviceIds: deviceIds,
      createdUsers: createdUsers,
    });
    await apiLogin('test11', 'Test111', defaultDeviceHeaders(device), {
      selectedRole: account,
    });

    await login.login('test11', 'Test111');
    await t.eval(() => location.reload());

    if (account === 'ROLE A') {
      await t
        .expect(roleSelection.roleAModalTitle.visible)
        .ok('Logged in as role A modal not visible', { timeout: 5000 });
    } else {
      await t
        .expect(roleSelection.roleBModalTitle.visible)
        .ok('Logged in as role B modal not visible', { timeout: 5000 });
    }
  });
});

apiLogin method:

export function apiLogin(
  username: string,
  password: string,
  headers?: {},
  query: { selectedRole?: string } = {},
) {
  return request(config.CONFIG.TOKEN_GENERATOR)
    .post(`/login`)
    .auth(username, password)
    .set(headers)
    .query(query);
}

Managing Multiple Firebase SDK Versions in a Large Project

I’m working on a large web application that utilizes several Firebase services (Authentication, Firestore, Cloud Functions, etc.). Over time, different parts of the application have been developed using different versions of the Firebase SDK. This has led to some inconsistencies and potential conflicts.

Currently, I’m facing challenges with:

  • Dependency Management: Keeping track of which SDK versions are used where is becoming a nightmare. We’re using npm and have a package.json but it’s getting complex.
  • Potential Conflicts: We’re concerned about potential conflicts arising from using different versions of the SDK simultaneously.
  • Upgrade Strategy: We want to upgrade to the latest Firebase SDK version across the board, but doing so all at once is a daunting task.

Are there any specific considerations when managing Firebase SDK versions in a monorepo environment? I’m looking for advice on best practices, tools, and strategies for managing Firebase SDK versions effectively in a large project.

Key unwrapping fails

I want to protect a RSA private key stored in localStorage by wrapping it with a key derived from the user’s password.

When registering a new account:

// Generate RSA key pair

const keyPair = await crypto.subtle.generateKey({
    name: "RSA-OAEP",
    modulusLength: 4096,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: "SHA-512"
}, true, ["encrypt", "decrypt"]);

// Save private key

// Encrypt the private key

const textEncoder = new TextEncoder();
const salt = new Uint8Array(16);

crypto.getRandomValues(salt);

const passwordKey = await crypto.subtle.importKey("raw", textEncoder.encode(passwordInput.value), "PBKDF2", true, ["deriveKey"]);
const derivedKey = await crypto.subtle.deriveKey({
    name: "PBKDF2",
    hash: "SHA-512",
    salt,
    iterations: 210000
}, passwordKey, {
    name: "AES-CBC",
    length: 256
}, true, ["wrapKey", "unwrapKey"]);
const iv = new Uint8Array(16);

crypto.getRandomValues(iv);

const wrappedPrivateKey = await crypto.subtle.wrapKey("pkcs8", keyPair.privateKey, derivedKey, {
    name: "AES-CBC",
    iv
});
const userId = resData.id;

sessionStorage.setItem("crypto-key", bufferToBase64(privateKey));
localStorage.setItem(`crypto-key-${userId}`, bufferToBase64(wrappedPrivateKey));
localStorage.setItem(`crypto-key-${userId}-salt`, bufferToBase64(salt));
localStorage.setItem(`crypto-key-${userId}-iv`, bufferToBase64(iv));
}

When logging in:

// Decrypt the private key

const userId = resData.id;
const textEncoder = new TextEncoder();
const encryptedPrivateKey = base64ToArrayBuffer(localStorage.getItem(`crypto-key-${userId}`));
const salt = base64ToArrayBuffer(localStorage.getItem(`crypto-key-${userId}-salt`));
const iv = base64ToArrayBuffer(localStorage.getItem(`crypto-key-${userId}-iv`));
const passwordKey = await crypto.subtle.importKey("raw", textEncoder.encode(passwordInput.value), "PBKDF2", true, ["deriveKey"]);
const unwrappingKey = await crypto.subtle.deriveKey({
    name: "PBKDF2",
    hash: "SHA-512",
    salt,
    iterations: 210000
}, passwordKey, {
    name: "AES-CBC",
    length: 256
}, true, ["unwrapKey"]);

const privateKey = await crypto.subtle.unwrapKey("pkcs8", encryptedPrivateKey, unwrappingKey, {
    name: "AES-CBC",
    iv
}, {
    name: "RSA-OAEP",
    hash: "SHA-512"
}, true, ["encrypt", "decrypt"]);

sessionStorage.setItem("crypto-key", bufferToBase64(privateKey));

location.reload();

These are the helper functions for encoding/decoding

const base64ToArrayBuffer = (data) => {
    const binaryKey = atob(data);
    const keyBytes = new Uint8Array(binaryKey.length);

    for (let i = 0; i < binaryKey.length; i++) {
        keyBytes[i] = binaryKey.charCodeAt(i);
    }

    return keyBytes.buffer;
}

const bufferToBase64 = (data) => btoa(String.fromCharCode(... new Uint8Array(data)));

However when unwrapping the key the error DOMException: An invalid or illegal string was specified is thrown.

Security is considered up to a certain point because this is just a demo project.

Why Is My Image Map Not Working Properly?

I made an image map in HubSpot, and I got the image to show up properly. But none of the awards/badges take the user to the websites I’m trying to link each icon to.

I’ve linked the webpage in question here, and you can view the code below:

<img src="https://tricomts.com/hubfs/Awards%20and%20Badges/025_Thought%20Leadership-Badges.png" usemap="#image-map">
<map name="image-map">
   <area title="Talent" alt="Talent" coords="795,667,419" shape="circle" href="https://www.clearlyrated.com/staffing/ks-usa/leawood-ks/tricom-technical-services-leawood-ks" target="_blank">
   <area title="Client" alt="Client" coords="2045,657,434" shape="circle" href="https://www.clearlyrated.com/staffing/ks-usa/leawood-ks/tricom-technical-services-leawood-ks" target="_blank">
   <area title="SIA" alt="SIA" coords="2869,432,4705,874" shape="rect" href="https://www.staffingindustry.com/lists/best-staffing-firms-to-work-for-in-north-america/2024-best-staffing-firms-to-work-for" target="_blank">
   <area title="Google" alt="Google" coords="313,1360,1690,1987" shape="rect" href="https://www.google.com/search?q=TriCom+Technical+Services&amp;rlz=1C1GCEA_enUS1145US1145&amp;oq=tri&amp;gs_lcrp=EgZjaHJvbWUqBggBEEUYOzIGCAAQRRhBMgYIARBFGDsyBggCEEUYOzIGCAMQRRg7MgYIBBBFGDwyBggFEEUYPDIGCAYQRRg9MgYIBxBFGEHSAQg0MjY4ajBqNKgCALACAA&amp;sourceid=chrome&amp;ie=UTF-8#mpd=~16213571407237096531/customers/reviews" target="_blank">
   <area title="GreatRecruiters" alt="GreatRecruiters" coords="2070,1306,3473,1941" shape="rect" href="https://app.greatrecruiters.com/companies/tricom-technical-services" target="_blank">
   <area title="Glassdoor" alt="Glassdoor" coords="3817,1267,4700,1956" shape="rect" href="https://www.glassdoor.com/Reviews/TriCom-Technical-Services-Reviews-E271294.htm" target="_blank">
</map>

How to parse formData in nest.js?

I send an image and some accompanying fields, and due to image presence need to send request as FormData. In nest.js controller I extract image and body like shown in their documentation:

 @Post()
  @UseInterceptors(FileInterceptor('image'))
  async create(
    @UploadedFile()
    filename: any,
    @Body()
    data: any,
  ) {
   ...
  }

And here I have a problem, I have not only strings, but booleans and arrays. I send them from front-end with JSON.stringify, and in nest.js I want to JSON.parse them, to convert them back from strings to booleans and arrays. I want to loop through data object that @Body decorator outputs to parse all the fields, but it’s not iterable. It’s not a formData either, as formData methods don’t work on it.

How am I supposed to convert formData strings back to booleans/arrays? Is there maybe some other decorator? Or built-in pipe? I don’t want to parse each field manually, I want to be able to loop through them.

how i can fix shake and vibration centered image when width is changes?

I beginner and trying to create navigation bar at small project.
everything is good but when width is changing, it have vibration and shake:
My logo on center of navigation bar will shake when width is changing

const stickyElement = document.getElementById('headerMenu');
window.addEventListener('scroll', () => {
  const rect = stickyElement.getBoundingClientRect();
  if (rect.top <= 15) {
    // stickyElement.style.width = getComputedStyle(stickyElement).width;
    console.log(getComputedStyle(stickyElement).width)
    requestAnimationFrame(() => {
        stickyElement.style.width = "76vw";
      })
  } else {
        if (window.innerWidth <= 800) {
            stickyElement.style.width = "90%";
        } else {
            stickyElement.style.width = "95%";
        }
  }
});
body {
    text-align: center;
    padding: 0px 4px 0px 4px;
    margin: 0px;
    height: 2000px;
    background-image: linear-gradient( to bottom, black,rgb(87, 87, 87));
    background-size: contain;
}
@font-face {
    font-family: Lato;
    src: url(Lato/Lato-Light.ttf);
}   
a {
    text-decoration: none;
}
h1, #header {
    margin: 0px;
    padding: 0px;
}
#headerMenu {
    width: 95%;
    margin: auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0px 20px 0px 20px;
    backdrop-filter: blur(10px) grayscale(1) brightness(0.7);
    height: 50px;
    border-radius: 10px 10px 20px 20px;
    position: sticky;
    top: 10px;
    margin-top: 250px;
    overflow: visible;
    transition: width 1s ease;
}

#headerImg {
    border-radius: 20px;
    padding: 10px;
    flex-shrink: 1;
    flex-grow: 0;
    margin: 0px 10px;
    animation-name: scaleUpDown;
    animation-iteration-count: infinite;
    animation-direction: alternate-reverse;
    animation-duration: 1s;
    transform: translateX(50%);
}
@media screen and (max-width:800px) {
    #headerMenu {
        width: 80%;
    }
}

.headerSidesMenu {
    align-items: center;
    padding: 0px;
    display: flex;
    flex-basis: 45%;
    list-style-type: none;
    overflow-x: visible;
    height: 100%;
    scrollbar-width: none;
    overflow-y: auto;
}
.headerSidesMenu > li {
    
    margin: 0px;
    height: 100%;
    padding: 0px 0px;
    font-family: Lato,monospace;
    overflow-x: visible;
    background-color: transparent;
    transition: background-color .2s, transform .5s;
}
.headerSidesMenu > li > a {
    color: white;
    transform: translateY(-5%);
    line-height: 0px;
    margin: 0px;
    display: flex;
    align-content: center;
    align-items: center;
    overflow-x: visible;
    padding: 0px 20px;
    padding-top: auto;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}
.headerSidesMenu > li > a::after {
    content: "♠";
    position: absolute;
    right: 0px;
    opacity: 0;
    transition: opacity 0.3s, right 0.5s, left 0.5s;
}
.headerSidesMenu > li:hover {
    transition: background-color .2s, transform .5s;
    transform: translateX(-7px);
}
.headerSidesMenu > li:hover > a::after {
    right: 8px;
    transition: opacity 0.3s, right 0.5s;
    opacity: 1;
}
#rightMenu {
    flex-direction: row-reverse;
}
#rightMenu > li:hover {
    transition: background-color .2s, transform .5s;
    transform: translateX(+7px);
}
#rightMenu > li > a::after  {
    left: calc(-60% - 10px);
    transition: opacity 0.3s, right 0.5s, left 0.5s;
}
#rightMenu > li:hover > a::after {
    left: -60%;
    transition: opacity 0.3s, right 0.5s, left 0.5s;
}
@keyframes scaleUpDown {
    from {transform: scale(1);}
    to {transform: scale(1.3);}
};
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>My page testing</title>
        <link rel="stylesheet" href="myPageTesting.css" />
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        
    </head>
    <body>
        <div id="headerMenu">
            <ul id="leftMenu" class="headerSidesMenu">
                <li><a href="myPageTesting.html">Home</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
            </ul>
            <img src="https://i.ibb.co/0yJ11hYF/myLogo.png" alt="MojiJon" width="70px" height="70px" id="headerImg">
            <ul id="rightMenu" class="headerSidesMenu">
                <li><a href="myPageTesting.html">Home</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
                <li><a href="soon.html">soon1</a></li>
            </ul>
        </div>
        <script src="myPageTesting.js"></script>
    </body>
</html>

Please help me how i can fix this problem.

i trying to add position:absolute; to #headerImg, my problem fixed but i cant stay image on center when width element and window changes

Why am I able to send this form if the Nombre and Apellido inputs are filled but there’s still errors present?

Problem: I have to make a form with some inputs (name, surname, etc) check the filled information is correct and if it is sent it. The thing is;

  • If the form is empty it doesn’t send

  • if the form is correctly filled it sends

  • if there’s any error present (DNI and/or phone number not correctly formatted, name or surname empty and terms not checked) it doesn’t send BUT if the ‘nombre’ and ‘apellido1’ fields are filled with at least one character it sends ignoring all other errors, (I tried several combinations) and I don’t know why or what am I doing wrong

Here it is the code to the form (without CSS styles)

(For clarification, spanish phone numbers start with 6 or 7 and followed by 8 numbers, DNI is 8 numbers and one letter, check the regex)

<body>


    <!--Contenido de la página-->


    <div class="formulario">


        <!--Establecemos que las funciones se hagan al llamar los botones de "enviar" y "reset";
        "onsubmit" hace las comprobaciones al pulsar enviar, y "onreset" reestablece el contenido al pulsar reset
        action:"mailto..." hace que si todo está OK envíe el formulario. Esto lo sabemos porque abre un cuadro de diálogo
        donde nos pregunta con qué aplicación de correo enviarlo-->


        <form id="formulario" name="formulario" onsubmit="return validform()" onreset="resetErrores()" action="mailto:[email protected]">
            <fieldset>
                <legend>Formulario de registro</legend>
                <p>Los campos marcados con asterisco(*) son obligatorios</p>
                    <h1>Nombre y apellidos</h1>


                        <label for="nombre">Nombre*</label><br>
                            <input type="text" id="nombre" name="nombre"><br>
                                <span id="nombreErr" class="error"></span><br>


                        <label for="apellido1">Primer apellido*</label><br>
                            <input type="text" id="apellido1" name="apellido1"><br>
                                <span id="apellidoError" class="error"></span><br>


                        <label for="apellido2">Segundo apellido</label><br>
                            <input type="text" id="apellido2" name="apellido2"><br>


                    <h1>Número de teléfono</h1>
                        <label for="movil">Teléfono movi*</label><br>
                            <input type="text" id="movil" name="movil"><br>
                                <span id="movilError" class="error"></span><br>
                        <label for="fijo">Teléfono fijo</label><br>
                            <input type="text" id="fijo" name="fijo"><br>
                                <span id="fijoError" class="error"></span><br>
                    <h1>DNI</h1>
                        <label for="dni">Número de DNI*</label><br>
                            <input type="text" id="dni" name="dni"><br>
                                <span id="dniError" class="error"></span><br>


                    <h1>Cumpleaños</h1>
                        <label for="cumple">Fecha de nacimiento</label><br>



                        <!--Acortamos la fecha de hoy mediante el onfocus del input date-->


                            <input type="date" id="cumple" name="cumple" max="3000-01-01" onfocus="this.max=new Date().toISOString().split('T')[0]">


                <div class="botones2">
                    <input type="checkbox" name="terminos" id="terminos">Acepto los términos y blah, blah, blah<br>
                        <span id ="aceptarError" class="error"></span><br>
                    <input type="checkbox" name="spam" id="spam">Quiero que me llenéis el correo de spam<br>
                </div>
                <div class="botones">
                    <input type="reset" value="Reset" id="Reset">
                    <input type="submit" value="Enviar" id="Enviar">
                </div>
            </fieldset>
        </form>
    </div>
<script>


    function validform(){


        /*Declaramos las distintas constantes: los inputs que se van a comprobar, los errores a mostrar y 
        las expresiones regulares para el móvil y el DNI
        */


        const nombre = document.getElementById("nombre").value;
        const apellido1 = document.getElementById("apellido1").value;
        const movil = document.getElementById("movil").value;
        const dni = document.getElementById("dni").value;
        const aceptar = document.getElementById("terminos").checked;
        const fijo = document.getElementById("fijo").value;


        const nombreErr = document.getElementById("nombreErr");
        const apellidoError = document.getElementById("apellidoError");
        const movilError = document.getElementById("movilError");
        const dniError = document.getElementById("dniError");
        const aceptarError = document.getElementById("aceptarError");
        const fijoError = document.getElementById("fijoError")


        const regexMovil = /^[67]d{8}$/;
        const regexFijo = /^[89]d{8}$/;
        const regexdni = /^[0-9]{8}[TRWAGMYFPDXBNJZSQVHLCKE-trawagmyfpdxbnjzsqvhlcke]$/;


        /*establecemos que el contenido de los errores esté vacío por defecto*/


        nombreErr.textContent = "";
        apellidoError.textContent = "";
        movilError.textContent = "";
        dniError.textContent = "";
        aceptarError.textContent = "";
        fijoError.textContent = "";


        /*establecemos Valido como ture para que si hay un error se convierta en falso. Si Valido es falso, el formulario
        no se envia */


        let Valido = true;


        /*realizamos las comprobaciones de los campos obligatorios*/


        if (nombre === "") {
            nombreErr.textContent = "Introduce un nombre!!";
            Valido = false;
        } 


        if (apellido1 === "") {
            apellidoError.textContent = "Introduce el primer apellido!!";
            Valido = false;
        }


        if (!regexMovil.test(movil)) {
            movilError.textContent = "Introduce un móvil válido!!";
            valido = false;
        }


        if (!regexdni.test(dni)){
            dniError.textContent = "Introduce un DNI válido!!";
            valido = false;
        }


        if (!aceptar) {
            aceptarError.textContent = "Acepta los términos!!";
            valido = false;
        }


        if (fijo !== "" && !regexFijo.test(fijo)) {
            fijoError.textContent = "Introduce un fijo válido!!";
            valido = false;
        }


        if (Valido) {
            alert ("formulario enviado correctamente");
            return true;
        } else {
            return false;
        }
    }


/*Reseteamos los mensajes de error*/


    function resetErrores() {
        document.getElementById("nombreErr").textContent = "";
        document.getElementById("apellidoError").textContent = "";
        document.getElementById("movilError").textContent = "";
        document.getElementById("dniError").textContent = "";
        document.getElementById("aceptarError").textContent = "";
        document.getElementById("fijoError").textContent = "";
    }


</script>
</body>
</html>

Basically what I said, if there’s any errors present it doesn’t send, but if the Nombre (name) and Primer apellido (first surname) it ignores any error

Facing Issue with setting up a PWA Service Worker

I have a React + Laravel web app, and I would like to add a Service Worker to enable offline access and other PWA features such as push notifications.

I’ve created an SSL certificate and my app is now served via a self-signed certificate at: https://example.com.

I created an app.js file under the resources/js directory with the following code to register the service worker service:

require('./bootstrap');

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js')
      .then((registration) => {
        console.log('Service Worker registered with scope:', registration.scope);
      })
      .catch((error) => {
        console.error('Service Worker registration failed:', error);
      });
  });
}

When I open the app in Firefox, I see the message:
Service Worker registered with scope: https://infypos.test/ in the console.
However, when I check about:serviceworkers, there is no service worker registered.

How should I debug this? or if there are any other ways to register the service worker?

ReactGrid Popover Input Field Not Receiving Focus Upon Opening

enter image description here

In the image as you can see i have added a Popover on the react grid
lib – @silevis/reactgrid

I’m working with ReactGrid and have implemented a custom cell renderer that opens a popover containing input fields for editing cell values. However, when the popover opens, the input fields inside it do not receive focus as expected. Instead, the focus seems to remain on the grid, preventing user interaction with the inputs

What I’ve Tried:

Using useRef to reference the input elements and calling .focus() on them inside a useEffect hook when the popover opens.

Blurring the grid’s internal focus element (.rg-hidden-element) before focusing the input.

Wrapping the popover content in a ReactDOM.createPortal to render it outside the grid’s DOM hierarchy.

Despite these attempts, the input fields still do not receive focus when the popover opens.

Expected Behavior:

When the popover opens, the first input field inside it should automatically receive focus, allowing the user to start typing immediately.

Actual Behavior:

The input fields inside the popover do not receive focus upon opening. The focus remains on the grid, and the user must manually click on the input field to start typing.

useEffect(() => {
    if (showModal) {
        const rgHidden = document.querySelector(".rg-hidden-element") as HTMLElement;
        rgHidden?.blur();
        setTimeout(() => inputRef.current?.focus(), 0);
}
}, [showModal]);

How can I ensure that the input field inside the popover receives focus automatically when the popover opens in ReactGrid?

How to fix ‘TypeError: undefined is not a function’ in JavaScript? [closed]

Goal:
I’m trying to call a function in my JavaScript code, but I keep getting the error:
TypeError: undefined is not a function.

Expected vs. Actual Results:

Expected: The function should execute without errors.

Actual: The error occurs, and the function doesn’t run.

Error Context:
The error happens when I call myFunction() in this snippet:

JavaScript (the issue arises in a larger project, but the simplified example below replicates it)

let myFunction = undefined;
myFunction(); // Throws "TypeError: undefined is not a function"

What I’ve Tried:

Checked if the function is properly defined before calling it.

Verified that there are no typos in the function name.

Confirmed the function is in scope (not blocked by conditional logic).

Browser: Chrome (latest version).

Question:
What are the common causes of this error, and how can I debug/fix it?

In React + TypeScript, when should a prop be prop?: Type vs prop: Type | undefined? [duplicate]

When designing TypeScript props for React components,
I’m sometimes unsure whether I should type props like:

prop?: Type

or

prop: Type | undefined

My understanding so far:

prop?: Type

The prop itself is optional — the component can be used without passing this prop.

If the prop is passed, it must be of the given Type.

prop: Type | undefined

The prop is required — it must be passed every time,

but the value itself can be undefined.

The confusion:

In some cases, a prop is critical for logic inside the component (I will always use it),
but at runtime, it might temporarily be undefined during early renders or initialization.

Questions:

When should I prefer prop?: Type vs prop: Type | undefined?

Is it acceptable to use ?: even if the value is temporarily undefined at first?

What is considered the cleanest or most “production-quality” way to handle this in modern React + TypeScript projects?

How do large real-world applications typically approach this?