How does the reducer function know that count is a state’s item?

I do not understand how reducer knows that count is from state without using state’s name in the code. I thought it was like “return {state.count: state.count + 1}“. How does it work?

import { useReducer } from 'react';
    
    const initialState = {count: 0};
    
    const reducer = (state, action) =>{
      switch(action.type){
        case 'minus':
          return {count: state.count + 1}
        break;
        case 'plus':
          return {count: state.count - 1}
        break;
        case 'reset':
          return initialState;
        break;
      }
      return state;
    }
    
    const App = () =>{
      const [state, dispatch] = useReducer(reducer, initialState);
    
      return(
        <div>
          <button onClick={() => dispatch({type: 'menos'})}>-</button>
          <div>{state.count}</div>
          <button onClick={() => dispatch({type: 'mais'})}>+</button>
          <button onClick={() => dispatch({type: 'reset'})}>reset</button>
        </div>
      );
    }
    
    export default App;

Unable to access property in javascript file in react component

I am building a chrome extension, which uses react/webpack, and it needs to inject code into an existing page. So I need to load one of my javascript files when the component is rendered.

However, I cannot access properties in that javascript file. I get error ‘Cannot read properties of undefined (reading ‘initialvalue’)‘. I have given the manifest.json file all the proper permissions and I know the script file is loading correctly. What am I doing wrong?

plugin.bundle.js (javascript file I’m trying to load)

var plugin = plugin || {};

SetupPlugin();
function SetupPlugin() {
    plugin.initialvalue = plugin.initialvalue || 123;
}

index.jsx

import { render } from 'react-dom';
import Embedtab from './Embedtab';

render(<Embedtab />, window.document.body.querySelector('.someclass'));

Embedtab.tsx

declare global {
  interface Window {
    plugin: any;
  }
}

export class Embedtab extends React.Component<any> {
  componentDidMount() {
    const script = document.createElement("script");
    script.src = chrome.runtime.getURL("./../plugin.bundle.js");
    script.async = false;
    script.onload = () => this.scriptLoaded();

    document.body.appendChild(script);
  }

  scriptLoaded() {
    alert("embedded loaded, value is " + window.plugin.initialvalue); //errors here
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          Hello World
        </header>
      </div>
    );
  }
};

export default Embedtab;

Variable in React is undefined on first render but defined after re-rendering. (Uncaught TypeError: vairable is undefined)

When I try to show the title of a movie (line 8 of App.js) I get the error “Uncaught TypeError: movies[0] is undefined”. If I do a log of the variable “movies” after line 5 the console makes two logs: Frist, logs movies as an empty array and then logs movies as an array with all the content, like I want.

The weird thing is that if I delete the line 8 {movies[0].title} and save the error dissapears as normal, but then if I add it again and save the movie title renders on screen like I’m trying to do.

App.js:

import './App.css';
import useApi from './useApi';

function App() {
  const movies = useApi();
  return (
    <div className="App">
      {movies[0].title}
    </div>
  );    
}

export default App;

My useApi returns an array with a list of movies:

import axios from 'axios';
import { useState, useEffect } from 'react';

const useApi = () => {
    const [movies, setMovies] = useState([]);

    const getData = async () => {
        try {
            const res = await axios(url);
            setMovies(res.data.results);
        } catch (error) {
            return [];
        }
    }

    useEffect(() => {
        getData();
    }, [])

    return movies;
}

export default useApi;

Knowing that if I print movies it logs an empty array but then it prints it normal like I said, i guess I’m having a problem with asynchrony but I can’t figure out what. And the fact that it works when removing and readding line 8 makes me more confused.

How to change the left position of div instance with arrow key using javascript?

I am new to javascript, please bear with me.
When the right arrow key is pressed I would like to change the div 100 pixels to the right. I use my own class to create a square and then try to change this instance position.

class Square {
  constructor(length) {
    this.width = length;
    this.height = length;

    this.div = document.createElement("div");
    this.div.style.position = "absolute"; // to be able to move it
    this.div.style.backgroundColor = "red";
    this.div.style.width = length + "px";
    this.div.style.height = length + "px";
    document.body.appendChild(this.div);

    this.xPos = 50;
    this.div.style.left = this.xPos + "px";

  }
}

var square2 = new Square(10);

window.addEventListener(
  "keydown",
  function (event) {
    if (event.defaultPrevented) {
      return; // Do nothing if the event was already processed
    }

    switch (event.key) {
      case "ArrowDown":
        alert("ArrowDown");
        // Do something for "down arrow" key press.
        break;

      case "ArrowUp":
        // Do something for "up arrow" key press.
        break;

      case "ArrowLeft":
        alert("ArrowLeft");
        // Do something for "left arrow" key press.
        break;

      case "ArrowRight":
        alert("ArrowRight");
        square2.div.style.left += 100 + "px"; // this code does nothing?
        
        break;

      default:
        return; // Quit when this doesn't handle the key event.
    }

    // Cancel the default action to avoid it being handled twice
    event.preventDefault();
  },
  true
);

The code square2.div.style.left += 100 + "px"; does nothing.

(Javascript) Why can I not refer to my function with this inside of a child object? [duplicate]

so this is the code i wrote:

const PersonProto = {
  calcAge() {
    return 2022 - this.birthYear;
  },

  init(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  },
};

const walter = Object.create(PersonProto);

const StudentProto = Object.create(PersonProto);
StudentProto.init = function (firstName, birthYear, course) {
  PersonProto.init.call(this, firstName, birthYear);
  this.course = course;
};

StudentProto.introduce = function () {
  console.log(
    `hi i am ${this.firstName} who is ${this.calcAge} years old and is studying ${this.course}`
  );
};

const penny = Object.create(StudentProto);
penny.init('Penny', 2021, 'maths');
penny.calcAge();
penny.introduce();

and the problem is that for penny.introduce(), I get

hi i am Penny who is calcAge() {
    return 2022 - this.birthYear;
  } years old and is studying maths

in the console. However penny.calcAge() does work correctly. So why does it not work inside of the other function? I’m just starting to learn about inheritance and prototypes so it’s hard for me to figure this out by myself. Thanks in advance, any help is welcome!

MongoDB JS 304 StatusCode

First of all I’m extremely sorry but i can’t figure out what the title should be,
I’m trying to send data to MongoDB Database but for some reason, I keep getting 304 status code, I tried searching it on the internet but I couldn’t find a solution, and was hard for me to understand, can you guys please help me?

Here’s the data I’m trying to send to DB

  const router = require("express").Router();
  const User = require("../models/User");



 router.get("/register", async (req,res) => {
 const user = await new User ({
 username:"username",
  email:"[email protected]",
  password:"123456"
  })
 await user.save();
 res.send("okk!");

});


module.exports = router;

//
MongooseError: Operation users.insertOne() buffering timed out after 10000ms
at Timeout. node_modulesmongooselibdriversnode-mongodb-nativecollection.js:151:23)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)

Why am I getting axios.get is not a function?

I’m realtively new to Node and so I am trying to iron out some of the creases.

I’ve been trying to get used to working with packages and npm and decided to start by importing axios to make a simple http request.

I successfully initialised the project using npm init.

The first issue I encountered was when I tried to run npm install axios, this returned the following error:

npm ERR! code ENOTDIR
npm ERR! syscall mkdir
npm ERR! path G:My DriveNodeJSAnother Package Examplenode_modules
npm ERR! errno -4052
npm ERR! ENOTDIR: not a directory, mkdir 'G:My DriveNodeJSAnother Package Examplenode_modules'

In order to try and resolve this I used the command provided by the error i.e. mkdir ‘G:My DriveNodeJSAnother Package Examplenode_modules’, was this the correct thing to do? This created the node_modules folder and when I tried to run npm install axios I didn’t get an error, but instead:

npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write

added 8 packages, and audited 9 packages in 2s

1 package is looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Below is the code I wrote for my request.js file:

const axios = require('axios');

axios.get('https://www.google.com')
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

However, when I try to run the code using node request.js I get the below response:

.get('https://www.google.com')
   ^

TypeError: axios.get is not a function
    at Object.<anonymous> (G:My DriveNodeJSAnother Package Examplerequest.js:4:4)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Furthermore, if I open my node_modules folder and open any of the files they appear to all be empty, which I’m assuming is causing this issue but I’m not 100% sure.

I have tried, removing the node_modules folder and inputting the command again but that didn’t work.

How to make horizontal scroll smoother?

I added this code to my WordPress based website to make its front page horizontal. But it’s not smooth and I cannot add scroll snap or anchor points. Can you help me about these? My website is https://kozb.art

function replaceVerticalScrollByHorizontal( event ) {
  if ( event.deltaY !== 0 ) {
   window.scroll(window.scrollX + event.deltaY * 2, window.scrollY );
   event.preventDefault();
  }
 }

 const mediaQuery = window.matchMedia( '(min-width: 770px)' );

 if ( mediaQuery.matches ) {
  window.addEventListener( 'wheel', replaceVerticalScrollByHorizontal );
 }
</script>```

Option box not appearing below the box

Is there any reason why this is happening?the option box is not appearing below the box itself

The option appears normally on big screen, it’s just when I inspect and make it responsive it seems like the option box is not moving at all? are there any particular details why?

I am a new developer and would like to know more on how to prevent this happening, and if someone please tell me why it’s happening too? thank you

html code:

    <!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">
    <!-- meta name/property starts -->
    <meta name="description" content="CDA offers driving lessons in Cambridge and surrounding areas extending all through Cambridgeshire. CDA has a fully-qualified team of instructors ">
    <meta property="og:title" content="Driving Lessons Cambridge | CDA">
    <meta property="og:description" content="CDA offers driving lessons in Cambridge and surrounding areas extending all through Cambridgeshire. CDA has a fully-qualified team of instructors ">
    <meta property="og:url" content="https://www.cambridgedrivingacademy.com">
    <meta property="og:site_name" content="cambridge driving ac">
    <meta property="og:type" content="website">
    <meta name="google-site-verification" content="-U4J2qSZr6SaN8sIfVFsM1Kl280vQ5CifW_lt12tbeo">
    <meta name="twitter:title" content="Driving Lessons Cambridge | CDA">
    <meta name="twitter:description" content="CDA offers driving lessons in Cambridge and surrounding areas extending all through Cambridgeshire. CDA has a fully-qualified team of instructors ">
    <!-- meta name close -->
    <title>CDA | Cambridge Driving Academy | Driving School in Cambridge</title>
    <!-- fas cdn -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
    <!-- personal css -->
    <link rel="stylesheet" href="/css/style.css" text="css">
    <link rel="stylesheet" href="/css/gallery.css" text="css">
    <!-- custom css -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.css">
    <link rel="stylesheet" href="/css/enrolment.css">
    <!-- swiper -->
    <link  rel="stylesheet"  href="https://unpkg.com/swiper@8/swiper-bundle.min.css" />
    <!-- llight gallery CDN -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightgallery-js/1.4.0/css/lightgallery.min.css">

</head>
<body>
    
    <!-- header section starts -->
        <header>
            <a href="#" class="logo">Cambridge <span>Driving Academy</span></a>
            <a href="#" ><img src="imgs/CDA_NEWLogo.png" class="img-logo" alt=""></a>
            <div class="navbar">
                <a href="#home">Home</a>
                <a href="index.html#courses">Courses</a>
                <a href="instructors.html">Team</a>
                <a href="index.html#about-us">About Us</a>
                <a href="training.html">Instructor Training</a>
                
                <a href="pricing.html">Prices</a>
            </div>
            <div class="icons">
                <i class="fa-solid fa-bars" id="menu-bars"></i>
                <a href="https://www.instagram.com/cambridgedriving/?hl=en" target="_blank">
                    <i class="fa-brands fa-instagram"></i>
                </a>
                <a href="https://www.facebook.com/cambridgedrivingacademy" target="_blank">
                    <i class="fa-brands fa-facebook">
                    </i></a>
                <a href="tel:07496 842781">
                    <i class="fa-solid fa-phone"></i>
                </a>
                
            </div>
        </header>
    <!-- ender ends -->

    <div class="enrolment-logo">
        <img src="/imgs/CDA_NEWLogo.png" alt="">
    </div>

    <!-- enrolment form starts -->
    <div class="cda-form" id="contact">

        <h1 class="heading">
            <span>Enrolment Form</span>
        </h1>
    
        <div class="row">


            <!-- <div class="image">
                <img src="/imgs/contact.png" alt="contact-us">
            </div> -->

            

 
    
            <form action="contact-form.php" method="POST">
    
                <span>Your Full Name</span>
                <input type="text" required placeholder="Enter your name" id="name" class="box" maxlength="40">
    
                <span>Your Email Address</span>
                <input type="email" required placeholder="Enter your email" id="email" class="box" maxlength="40">

                <span>Your Date of Birth</span>
                <input type="date" required placeholder="Enter your email" id="email" class="box" maxlength="40">

                <span>Your Address</span>
                <input type="text" required placeholder="First Line Address" id="email" class="box" maxlength="40">
                <input type="text"  placeholder="Second Line Address" id="email" class="box" maxlength="40">
                <input type="text"  placeholder="Third Line Adress" id="email" class="box" maxlength="40">
    
                <span>Your mobile number</span>
                <input type="text" required placeholder="Enter your mobile number" id="number" 
                class="box" maxlength="99999999999" onkeypress="if(this.value.length == 10) return false;">
    
                <span>Transmission Type </span>
                <select name="Courses" id="courses" class="box" required>
                    <option value="" disabled selected> Select Transmission --</option>
                    <option value="Manual Driving Course">Manual</option>
                    <option value="Automatic Driving Course">Automatic</option>
                </select>

                <span>Licence Type </span>
                <select name="Courses" id="courses" class="box" required>
                    <option value="" disabled selected> What type of licence do you have?</option>
                    <option value="Manual Driving Course">Provisional Licence</option>
                    <option value="Automatic Driving Course">
                        Full Automatic Licence</option>
                    <option value="Manual Driving Course">Full Licence</option>
                    <option value="Manual Driving Course">Foreign Licence</option>
                </select>

                <span>Your Driving Licence Number</span>
                <input type="email" required placeholder="Enter your Driving Licence Number" id="email" class="box" maxlength="40">
                
                <span>Theory Test </span>
                <select name="Courses" id="courses" class="box" required>
                    <option value="" disabled selected>Pass or Failed</option>
                    <option value="Manual Driving Course">Passed</option>
                    <option value="Automatic Driving Course">Failed</option>
                    <option value="Automatic Driving Course">Not Taken</option>
                </select>

                <span>Practical Test </span>
                <select name="Courses" id="courses" class="box" required>
                    <option value="" disabled selected>Pass or Failed</option>
                    <option value="Manual Driving Course">Passed</option>
                    <option value="Automatic Driving Course">Failed</option>
                    <option value="Automatic Driving Course">Not Taken</option>
                </select>

                <span>If you have an upcoming Theory and/or Practical Driving Test, please select one of the option </span>
                <select name="Courses" id="courses" class="box" required>
                    <option value="" disabled selected>Test booked --</option>
                    <option value="Manual Driving Course">Theory Test</option>
                    <option value="Automatic Driving Course">Driving Test</option>
                    <option value="Automatic Driving Course">Nothing Booked at the moment</option>
                </select>

                <Span>If you have already your Practical Driving Test booked, please provide booking reference number, test date, time and test centre:<Span>
                    <textarea name="message" id="message" cols="30" rows="3" placeholder="Type of test, Booking Ref #, Test Date, Time and Test Centre"></textarea>

                <Span>Driving Experience<Span>
                <textarea name="message" id="message" cols="30" rows="7" placeholder="Additional Information"></textarea>

            

                <h1 class="heading">
                    Parent/s or Guardian/s
                </h1>

                <span>Parents or Guardian's name</span>
                <input type="text" required placeholder="Enter your name, enter N/A if not applicable" id="name" class="box" maxlength="40">

                <span>Parents or Guardian's Email Address</span>
                <input type="text" required placeholder="Enter your guardian's email address, enter N/A if not applicable" id="name" class="box" maxlength="40">

                <span>Parents or Guardian's Contact Phone Number</span>
                <input type="text" required placeholder="Enter your guardian's contact number, enter N/A if not applicable" id="name" class="box" maxlength="40">


                
    
                <input type="submit" value="Submit Form" class="btn">
            </form>



        </div>
    
    </div>
    



    <!-- enrolment form ends -->
    




    <!-- scripts -->
        <script src="https://unpkg.com/swiper@8/swiper-bundle.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lightgallery-js/1.4.0/js/lightgallery.min.js"></script>
        <script src="/js/script.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.js"></script>
        

        <script>

            AOS.init({
                duration:800,
                offset:150,
            })

            lightGallery(document.querySelector('.gallery .gallery-container'));

            
        </script>

    <!-- script ends -->
</body>
</html>

css code :

.enrolment-logo img {
    height:8rem;
}

.enrolment-logo {
    text-align: center;
    margin-top:5%;
}

.cda-form {
    background-color: #fff;
    padding:2% 15%;
    text-align: center;
    width:80%;
    margin: 0 auto;
}

.cda-form .heading span {
    color:var(--primary-color);

}

.cda-form .row {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    gap:1.5rem;
}

.cda-form .row .image{
    flex: 1 1 40rem;
    text-align: center;
}

.cda-form .row .image img {
    width:60%;
}

.cda-form .row form  .box,textarea{

    width:100%;
    margin-top: 1rem;
    margin-bottom: 2rem;
    border-radius: .5rem;
    background-color:white;
    box-shadow: var(--box-shadow);
    font-size: 1.8rem;
    color:var(--black);
    resize: none;
    padding:1.4rem;
    font-family: 'Poppins', sans-serif;
}

.cda-form .row form  {
    flex: 1 1 20rem;

}
.cda-form .row form span {
    color:var(--primary-color);
    font-size: 1.6rem;
}
input,option {
    text-align: center;
}

::-webkit-input-placeholder {
    text-align: center;
 }
 
 :-moz-placeholder { /* Firefox 18- */
    text-align: center;  
 }
 
 ::-moz-placeholder {  /* Firefox 19+ */
    text-align: center;  
 }
 
 :-ms-input-placeholder {  
    text-align: center; 
 }


 @media(max-width:1400px){

    .enrolment-logo {
        text-align: center;
        margin-top:10%;
    }
    

}

@media(max-width:850px){

    .enrolment-logo {
        text-align: center;
        margin-top:20%;
    }
    .cda-form .heading span{
        font-size: 5rem;
    }

    .cda-form .row form  .box,textarea{

        font-size:1.5rem;
    }

}

@media(max-width:450px){

    .cda-form .heading span{
        font-size: 5rem;
        text-align: center;
        justify-content: center;
        display: flex;
    }
}

Next element with jQuery

I need to move on to the next element. My code shows 3 different cards and put the option in ddbb, but when click on the option I need to pass the ‘screen-view’ to the next card when sucess is ok.
I tried .next(‘.card’).toggle() and .show() but don’t work, any advice?

My template:

{% for standard in standards %}
<div class="card mx-auto mt-4" style="width: 95%;" data-aos="fade-up">
    <div class="card-header">
        <h5 class="card-title">Estándar {{standard.code}}</h5>
    </div>
    <div class="card-body">
        <p class="card-text">{{standard.name}}</p>
        <div class="card-text">
            <div class="table-responsive-sm tabla-standard" data-alternative-url="{% url 'answeruser' %}">
                <table class="table table-bordered">
                    <thead class="thead">
                        <tr>
                            {% for alternative in standard.alternative_set.visible %}
                            <th>
                                <div class="alternative color-{{forloop.counter}} {% if alternative.pk in answeruser_alternative_pks %} btnAlternativeFocus {% endif %}" data-alternative-pk="{{alternative.pk}}">
                                    <button class="btn btnAlternative-{{forloop.counter}}">{{alternative.name}}</button></div>
                            </th>
                            {% endfor %}
                        </tr>
                    </thead>
                    <tbody class="tbody">
                        <tr>
                            {% for alternative in standard.alternative_set.visible %}
                            <td>
                                <div class="alternativeDetail {% if alternative.pk in answeruser_alternative_pks %} btnAlternativeFocus {% endif %}">{{alternative.detail|safe|linebreaks}}</div>
                            </td>
                            {% endfor %}
                        </tr>
                    </tbody>
                    <tfoot class="tfoot">
                        <tr>
                            <th colspan="4">{{standard.diagnosis_tools|safe}}</th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

{% endfor %}


<script type="text/javascript">
    AOS.init({
        duration: 1200,
    })

    $(document).on('click', '.alternative', function () {
        const $this = $(this)
        const alternative_pk = $this.data('alternative-pk');
        console.log(alternative_pk)

        const url = $('.tabla-standard').data('alternative-url');
        $.ajax({
            type: "POST",
            url: url,
            // dataType: 'json',
            // contentType: "application/json; charset=utf-8",
            data: {
                'alternative_pk': alternative_pk,
                'csrfmiddlewaretoken': getCookie('csrftoken')
            }, // serializes the form's elements.
            success: function (json) {
                if (json.success) {
                    console.log("ok")
                }
            }
        });

        $this.next('.card').toggle();
    })
</script>

Please help ;_;

JavaScript. Задача с сравнением каждого элемента двух массивов [closed]

Дано 2 массива с 10 случайными числами. Нужно сравнить каждый элемент первого массива со вторым. Если такой элемент обнаружен, требуется вывести “1” в третий логовый массив и пропустить этот элемент первого массива, сразу перейдя ко второму. В ином случае, проверив оба массива и не обнаружив нужных элементов, требуется вывести “0” в логовый массив и перейти к следующему элементу первого массива. Всего в логе должно оказаться 10 элементов.

Скелет

HTML

        <b>A = </b><input type="text" id="inputF" class="inputFirstNum" size=50 value="">
        <button class="randArr1" onclick="randArr1()">Random</button>
        <b>B = </b><input type="text" id="inputS" class="inputSecondNum" size=50 value="">
        <button class="randArr2" onclick="randArr2()">Random</button>
        <button class="equal"onclick="equal()">Check</button>

JavaScript

function randArr(){
    let arr = [];
    for (let i = 0; i < 9; i++ ) {
        let a = Math.round( Math.random() * 100 );
        arr = arr +  a + ",";
        } 
    let b = Math.round( Math.random() * 100 );
    let res = arr + b;
    return res;
}

function randArr1(){
    inputF.value = randArr();
}

function randArr2(){
    inputS.value = randArr();
}

filter nested array of objects depending on children conditions

there is a tree of categories. its an array of objects (in this case 1 ob
ject with children property. children property is an array containing
or not containing other categories objects and so on ). Each object also has a property “disabled”.
It can be either true or false. The starting point is that some bottommost children “disabled”
are set to true. In this case all of them are set to true. The task is to find parents ids
which disabled have to be set to true if all of its children disabled are set to true. In
this particular case all parents ids have to be found because all bottommost children disabled
are set to true. My function returns only lowest level of parents. What am I doing wrong?

let parentIdsToDisable = [];
    function findParentIdsToDisable(tree) {
      tree.forEach((category) => {
        if (category.children.length > 0) {
          if (category.children.every((child) => child.disabled === true)) {
            category.disabled = true;
            parentIdsToDisable.push(category.id);
          }
        }
        findParentIdsToDisable(category.children);
      });
  }

const categories = [
  {
    id: 69,
    name: 'Прикраси',
    key: 'prykrasy',
    description: 'Прикраси',
    disabled: false,
    mpath: '69.',
    children: [
       {
        id: 70,
        name: 'Аксесуари',
        key: 'aksesyary-dlya-prykras',
        description: 'Аксесуари для прикрас',
        disabled: true,
        mpath: '69.70.',
        children: []
      },
       {
        id: 72,
        name: 'Ювелірні вироби',
        key: 'uvelirni-vyroby',
        description: 'Ювелірні вироби',
        disabled: false,
        mpath: '69.72.',
        children: [
          {
            id: 73,
            name: 'Срібло',
            key: 'vyroby-iz-sribla',
            description: 'Ювелірні вироби із срібла',
            disabled: true,
            mpath: '69.72.73.',
            children: []
          }
        ]
      },
       {
        id: 71,
        name: 'Біжутерія',
        key: 'bizhuteriya',
        description: 'Біжутерія',
        disabled: true,
        mpath: '69.71.',
        children: []
      }
    ]
  }
]

Can you stop a nested child node from executing its constructor until a parent node has constructed?

Imagine a scenario where I have the following DOM tree

<body>
  <parent-component>
    <div>
      <child-component></child-component>
    </div>
  </parent-component>
</body>

The child component has a seekParent function that fires off a CustomEvent that should be caught by the <parent-component>, which then uses a callback to tell the child this is the parent component node.

Consider when the child component is is defined via customElements.define() first. The child’s constructor fires off the CustomEvent as soon as <child-component> is defined, since parent nodes do not need to be valid and at this stage be HTMLUnknownElement.

The event bubbles through the <parent-component> without being caught because that component has not yet called its constructor, to attach an event listener.

Is it at all possible to not parse child nodes within a DOM tree until a parent becomes defined / valid Element? Otherwise, is there any way around this issue besides using a setTimeout()?

Thanks

download the pdf of component in react

I have a page that consist of a component that has a chart.js component. I use html2canvas and then jspdf for create a pdf of component but there is problem with chart.js on responsive mode .i want to chart in pdf be same as desktop chart but when screen resize the chart resize to based on width is there a way to fix this issue?