Access to internal consts of React component from parent

I have to access internal component constants to change component behaviour from parent.
Before I use many samples and FAQ (example is Stack overflow question and answers).

My component Viewer is:

import React from "react";

//imports...

export const Viewer = React.forwardRef((slides, ref) => {
    const viewerRef = React.useRef();
    const [open, setOpen] = React.useState(false);
    const [index, setIndex] = React.useState(0);

    React.useImperativeHandle(ref, () => ({
        show: (key) => {    // What I want to do from parent in details
            viewerRef.setIndex(key);
            viewerRef.setOpen(true);
        },
    }));

    return (
        <div>
            <Lightbox
                ref={viewerRef}
                open={open}
                slides={slides}
            />
        </div>
    );
});

Top-level component App is:

import React from "react";
import "./App.css";
import {Viewer} from "./Components/Viewer";

export default function App() {
    const slides = [
        //
    ]

    const refViewer = React.useRef(null)

    const handleOpenViewer = React.useCallback((key) => {
        refViewer.show(key)  // Runtime error here
    })
    
    return (
        <main>
            <div>
                <button
                    type="button"
                    onClick={handleOpenViewer(2)}
                >
                    Open Lightbox
                </button>
                <Viewer
                    ref={refViewer}
                    slides={slides} />
            </div>
        </main>
    );
}

Unfortunately, I’ve got the error refViewer.show is not a function (((
So, I cannot access to component constants from parent

No mouse events on canvas when using custom Google Maps type

I’m using a Custom Map Type to draw a canvas for each map tile. Once the tiles are loaded, I draw on those canvases based on the the tile and pixel position within the tile. I’m trying to add an addEventListener to detect mouse movement on the respective tiles. However, I’m not getting any mouse events as the Google Maps layer is handling those.

To get these mouse events, I believe I have to use a custom overlay and add the canvas element to the overlayMouseTarget via the onAdd() function.

Unfortunately, I’m not sure how to implement that within the custom map type I have. Here’s a function that illustrates what I’m currently working with. In this case, the canvas event listener never fires.

Where and how would I implement a per tile custom overlay here that would allow me to capture mouse events on the canvas element?

async function drawTest() {
    await google.maps.importLibrary("maps");

    var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 7,
      minZoom: 3,
      center: {lat: 38, lng: -5}
    });

    function CoordMapType(tileSize) {
      this.tileSize = tileSize;
    }

    CoordMapType.prototype.getTile = function(tile, zoom, ownerDocument) {
      const canvas = ownerDocument.createElement('canvas');
      canvas.id = "canvas_" + tile.x + "," + tile.y;
      canvas.width = 256;
      canvas.height = 256;
      canvas.addEventListener("mousemove", (e) => {
        console.log(e);
      });

      // Adding the overlay code here results in mouse events.
      // But the canvases appended to the center of the map.

      return canvas;
    };
    
    map.overlayMapTypes.insertAt(0, new CoordMapType(new google.maps.Size(256, 256)));

    let positions = [
      {tileX: 61, tileY: 48, pX: 100, pY: 200},
      {tileX: 62, tileY: 49, pX: 231, pY: 180},
    ]

    google.maps.event.addListener(map, 'tilesloaded', function() {
      for (let i = 0; i < positions.length; i++) {
        let canvas = document.getElementById("canvas_" + positions[i].tileX + "," + positions[i].tileY);
        let ctx = canvas.getContext("2d");
        ctx.fillStyle = "red";
        ctx.fillRect(positions[i].pX, positions[i].pY, 10, 10);
      }
    });
}
drawTest();

Thus far, I’ve tried implementing the following to getTile() as well as later after the tilesloaded listener occurs. This ends up appending all the canvases to a div in the center which offsets the canvas locations resulting in incorrect placement of the canvas drawings.

var CanvasOverlay = function() {};
CanvasOverlay.prototype = new google.maps.OverlayView();
CanvasOverlay.prototype.onAdd = function() {   
  console.log(tile)         
  let panes = this.getPanes();
  panes.overlayMouseTarget.appendChild(canvas);
};
var canvasOverlay = new CanvasOverlay();
canvasOverlay.setMap(map);

Here is a JSFiddle in case it helps visualize the issue.

https://jsfiddle.net/stjx1dkm/16/

Nodde.js Toad-Scheduler not Executing Tasks as Expected in Production Environment

I’m facing an issue with the Toad-Scheduler package in my Node.js application deployed to a production environment cyclic. While tasks run smoothly on localhost, they intermittently fail to execute on schedule in production, leading to irregular scheduling or complete cessation of task execution. I’ve ensured environment variables are correctly set, checked server logs for errors (none found), and verified server resource limits, but the problem persists. Seeking advice on troubleshooting steps, best practices, or known limitations when deploying Toad-Scheduler in a cloud-based hosting environment. Appreciate any insights or guidance. Thanks!

import express, { Express, Request, Response } from "express";
import dotenv from "dotenv";
import { connectDB } from "./config/db";
import { ToadScheduler, SimpleIntervalJob, Task } from 'toad-scheduler'
import Product from "./models/product";
import { automateSheet } from "./controllers/automate-sheet";


dotenv.config();

const app: Express = express();
const port = process.env.PORT || 4000;

const scheduler = new ToadScheduler();


app.get("/", (req: Request, res: Response) => {
  res.send("Creative Cod Bot Server");
});

connectDB()
  .then(async () => {
    app.listen(port, () => {
      console.log(`⚡️[server]: Server is running at http://localhost:${port}`);
    });

    const products = await Product.find();
    for (const product of products) {
      const task = new Task(product?.name, async () => {
         await automateSheet(product?._id);
      })
      const job = new SimpleIntervalJob({ seconds: product?.sheetDuration, }, task,{preventOverrun:true,id:product?.name})
      scheduler.addSimpleIntervalJob(job)
    }
  })

use a same module exporting to both main thread js and a web worker

Presently main.js uses a function f() from global.js, and webworker.js also uses f() via importScripts(‘./global.js’). It works. I am trying to translates everything the import-export way: but I fail.

New main.js

import {f} from ./global.js
//instead of nothing
async function(){
//...
const context = f();
}

New global.js (script with type=module)

export const NAME = "name";
export function f(){ /* ... */ }

New webworker.js called with new Worker(“webworker.js”, {type:’module’})

import {f} from ./global.js
//instead of importScripts('./global.js')
const samecontext = f();

There is a problem with main.js (async and import in module). Which is the correct way to declare the different scripts?

How can I use vanilla javascript to set up a mobile nav to function where clicking the parent nav item will search for a child ul item and add class?

I am trying to set up a mobile nav so that clicking a “parent” nav item will search for the sub-menu ul contained within and toggle an “active” class to make it appear. Bonus points to add a function where it closes any other “active” sub-menus when opening a new one

The default menu will have the sub-menus hidden unless the “active” class is added to it, but I need a way to check if the parent nav item is clicked before adding that to the corresponding sub-menu item within.

I tried the JS below (as well as some other methods) but what I’m missing is how to set up a loop where it checks if the parent menu item is clicked and if so toggle the active class on the child ul (sub-menu) within. Any help appreciated.

document.querySelectorAll('#menu-mobile .main-wrap ul > li').forEach((it) => {
  it.addEventListener('click', (ev) => {
     ev.preventDefault();
     it.querySelector('.sub-menu').classList.toggle('active');
  });
});
#menu-mobile {
position: fixed;
    top: 100px;
    overflow: auto;
    display: block;
    height: calc(100vh - 70px);
    width: 200px;
    right: 0;
    }

#menu-mobile .main-wrap {
    overflow: hidden;
    margin: 0;
    min-height: calc(10vh);
    position: relative;
    }

#menu-mobile .main-wrap ul > li {
    list-style: none;
    width: 100%;
    display: inline-block;
    padding-left: 15px;
    margin: 0;
    min-height: 50px;
    line-height: 50px;
    border-bottom: 1px solid #000;
    }
    
    #menu-mobile .main-wrap ul > li ul {
    display: none;
    opacity: 0;
    background-color: #333333;
    transition: opacity 0.25s ease;
    border-top: 1px solid #000000;
    }
    
   #menu-mobile .main-wrap ul > li ul.active {
    display: block;
    opacity: 1; 
    }
    
    
<div id="menu-mobile">
  <div class="main-wrap">
    <ul id="menu-mobile-menu">
      <li id="menu-item-12800">
        <a href="www.google.com">Menu Item 1</a>
        <ul class="sub-menu">
         <li id="menu-item-1263" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1263">
              <a href="www.google.com">Sub Menu Item 1</a>
          </li>
        </ul>
       </li>
        <li id="menu-item-12800">
        <a href="www.google.com">Menu Item 1</a>
        <ul class="sub-menu">
          <li id="menu-item-1264" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1264">
              <a href="www.google.com">Sub Menu Item 1</a>
          </li>
        </ul>
       </li>
    </ul>
    </div>
</div>

Javascript Template Literals issues

Wish i knew a way to rephrase this , but i really need help

Inside your template literal, create a label element and give it the text Entry # Name. Using your template literal syntax, replace # with the value of entryNumber.
const HTMLString = ;
}

I tried to handle it this way to no avail;

const HTMLString = <label for="entry${entryNumber}">Entry ${entryNumber} Name</label>;

Cookies visible in response but not getting saved

I am facing a problem that when I send request to my server for signin, I am able to see cookies in the network tab as response but it is not visible in application tab i.e. it does not get saved. I am using MERN stack for the project. Can someone help me out

Signin function (backend controller)

const UserSignin = async (req, res) => {
    try {
        const { email, password } = req.body;
        const userSchema = zod.object({
            email: zod.string().email(),
            password: zod.string().min(8)
        });
        const result = userSchema.safeParse({ email, password });
        if (result.error) {
            return res.status(411).json({
                message: `Incorrect inputs: ${result.error}`
            }); 
        }
        const user = await User.findOne({ email, password });
        if (!user) {
            return res.status(411).json({
                message: `Incorrect credentials`
            });
        }
        const jwt_token = jwt.sign({ userId: user._id }, JWT_SECRET);
        return res.status(200).cookie('authcookie', jwt_token, {
            maxAge: 900000,
            httpOnly: true
        }).json({
            message: "User logged in successfully",
            token: jwt_token
        });

    } catch (error) {
        console.log(error.message);
        return res.status(500).json({
            message: error.message
        });
    }
}

Making signin request(from frontend):

    const handleLogin= (e)=>{
    e.preventDefault();
    axios.post('http://localhost:3000/api/v1/user/signin', { email, password })
    .then( response=> {
    console.log(response);
    })
    .catch(error=>{
    console.log(error);
    })
    }

Slide transition animation not working in the css code

Here’s is the code in which I am trying to add animation of the sliding div elements how can i make it work

.slides{
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
.slider {
    overflow: hidden;
    width: 80%;
  }
  .slider ul {
    list-style: none; 
    padding: 0;
    margin: 0;
    display: flex;
    transition: transform 0.5s ease;
  }
  .slider ul li {
    width: 50%;
    padding: 20px;
    transition: transform 1s ease;
  }
  .slide {
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.05);
    padding: 40px;
    border-radius: 10px;
    color: #676767;
    line-height: 1.4;
  }
  .slide img {
    width: 100px;
    border-radius: 10px;
    margin-right: 10px;
    border: 4px solid #212ea0;
  }
  .user-info{
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      font-size: 15px;
  }
  .user-info h3{
      color: #212ea0;
  }

I tried to resolve the issue but all the other features of the unordered list is working fine only the transition is not visible.

Sorting only the top four items in an array and rearrange accordingly

I have created a race format for a Karting competition. Each race scores points and builds to make a drivers table.

Up until this point I have everything working fine.

The top 8 drivers go into semi-finals with the winner of the two semis progressing to a final.

I cannot work out how to sort correctly the final race, in the example I have presently the top four in the final list as 3,1,2,0 but I need the final four to list with race points 3,2,1,0 so the top of the Drivers table would list: (pos 1) Driver 10 as he won 3pts, (pos 2) Driver 15 as h

e won 2pts, (pos 3) Driver 17 as he gained 1pts and (pos 4) would be Driver 16.

This when sorted would have the top four drivers listed would be, 10, 5, 16, 3 - with the rest of the table remaining the same.

Here is the code I have: 

[text](<a class="jsbin-embed" href="https://jsbin.com/wipepew/1/embed?html,console,output">Driver Leaderboard</a><script src="https://static.jsbin.com/js/embed.min.js?4.1.8"></script>)


Feel free to amend.

I have almost got it working but cannot figure out how to sort the final race correctly.

Zoomband issue in lightningchart.js

I am using lightningchart.js to display an array of points (data) together with a zoomBandChart.

I can move the zoomband but it always stays between 0 an 10. See attached image.
enter image description here


        const dashboard = lightningChart()
          .Dashboard({
            numberOfColumns: 1,
            numberOfRows: 2,
            theme: Themes.darkGold,
          })
          .setRowHeight(0, 3)
        
        // Add XY Chart to top Cell in Dashboard.
        const chart = dashboard
          .createChartXY({
            columnIndex: 0,
            columnSpan: 1,
            rowIndex: 0,
            rowSpan: 1,
          })
          .setTitle('')
        
        chart
          .getDefaultAxisX()
          .setTickStrategy(AxisTickStrategies.Numeric)
        
        // Add Zoom Band Chart to bottom Cell in Dashboard.
        const zoomBandChart = dashboard.createZoomBandChart({
          columnIndex: 0,
          columnSpan: 1,
          rowIndex: 1,
          rowSpan: 1,
        })
        
        const lineSeries = chart.addLineSeries()
        const data = every50th.map((value, index) => ({ x: index , y: value }))
        lineSeries.add(data)
        zoomBandChart.add(lineSeries)

Player 2 Hits not registering

The collision box for Player 1 is recording hits and dropping Player 2 health correctly. Player 2 is not able to detect attack collisions. The code for player 2 is copy and paste from Player 1. All instances of “player.” changed to “enemy.” etc. FYI the determineWinner() function is still in progress, I am aware it’s not in the code currently.

<head>
    <style>
        * {
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <!--- Red Container Div-->
    <div style="position: relative;
                display: inline-block;">
        <!--- Smaller Container Div-->
        <div style="position: absolute;
                    display: flex;
                    width: 100%;
                    align-items: center;
                    padding: 20px;">
            <!--- Player Health --->
            <div style="position: relative;
                        height: 30px;
                        width: 100%;">
                <div style="background-color: rgba(0,0,0,.1);
                            height: 30px;
                            width: 100%;
                            border: 3px solid black;
                            border-radius: 5px;">
                </div>
                <div 
                    id="playerHealth" 
                    style="position: absolute;
                            background: blue;
                            border-radius: 5px;
                            top: 0;
                            right: 0;
                            bottom: 0;
                            left: 0;">
                </div>
            </div>
            <!--- Timer --->
            <div 
                id="timer"
                style="background-color: red;
                        border-radius: 20px;
                        padding: 2px;
                        height: 100px;
                        width: 100px;
                        flex-shrink: 0;
                        display: flex;
                        align-items: center;
                        justify-content: center;">
            60
            </div>
            <!--- Enemy Health --->
            <div style="position: relative;
                        height: 30px;
                        width: 100%;">
                <div style="background-color: rgba(0,0,0,.1);
                            height: 30px;
                            width: 100%;
                            border: 3px solid black;
                            border-radius: 5px;">
                </div>
                <div 
                    id="enemyHealth"
                    style="position: absolute;
                            background: blue;
                            border-radius: 5px;
                            top: 0;
                            right: 0;
                            bottom: 0;
                            left: 0;">
                </div>
            </div>
        </div>
        <!--- Text Display --->
        <div
            id="textDisplay"
            style="position: absolute;
                    color: white;
                    align-items: center;
                    justify-content: center;
                    top: 0;
                    right: 0;
                    left: 0;
                    bottom: 0;
                    display: none;">
        Tie
        </div>
        <canvas></canvas> 
    </div>
    <script src="./js/utils.js"></script>
    <script src="./js/classes.js"></script>
    <script src="Index.js"></script>
</body>
function rectangularCollision({rectangle1, rectangle2}) {
    return( 
        rectangle1.attackBox.position.x + rectangle1.attackBox.width >= rectangle2.position.x
        && rectangle1.attackBox.position.x <= rectangle2.position.x + rectangle2.width
        && rectangle1.attackBox.position.y + rectangle1.attackBox.height >= rectangle2.position.y
        && rectangle1.attackBox.position.y <= rectangle2.position.y + rectangle2.height
    )
};

//determine winner function
function determineWinner({player, enem, timerId}) {
    clearTimeout(timerId)
    document.querySelector("#textDisplay").style.display = "flex"
    if (player.health === enemy.health) {
            document.querySelector("#textDisplay").innerHTML = "No Victor"
        } else if (player.health > enemy.health) {
            document.querySelector("#textDisplay").innerHTML = "Player 1 Wins"
        } else if (player.health < enemy.health) {
            document.querySelector("#textDisplay").innerHTML = "Player 2 Wins"
        }
};

//Timer Function
let timer = 60;
let timerId
function decreaseTimer() {
    if (timer > 0) {
        timerId = setTimeout(decreaseTimer, 1000)
        timer-- 
        document.querySelector("#timer").innerHTML = timer
    }
    
    if (timer === 0) {
        determineWinner({player, enemy})
    }
};

/* Sprite Class */
class Sprite {
    constructor({ 
        position, 
        imageSrc, 
        scale = 1, 
        framesMax = 1,
        offset = {x: 0, y: 0},
    }) {
        this.position = position
        this.width = 50
        this.height = 150
        this.image = new Image()
        this.image.src = imageSrc
        this.scale = scale
        this.framesMax = framesMax
        this.framesCurrent = 0
        this.framesElapsed = 0
        this.framesHold = 15
        this.offset = offset
    }

    draw() {
        c.drawImage(
            this.image,
            this.framesCurrent * (this.image.width / this.framesMax),
            0,
            this.image.width / this.framesMax,
            this.image.height,
            this.position.x - this.offset.x, 
            this.position.y - this.offset.y, 
            (this.image.width / this.framesMax) * this.scale, 
            this.image.height * this.scale
        )
    }

    animateFrames() {
        this.framesElapsed++

        if (this.framesElapsed % this.framesHold === 0) {
            if (this.framesCurrent < this.framesMax - 1) {
                this.framesCurrent++
            } else  {
                this.framesCurrent = 0
            }
        }
    }

    update() {
        this.draw()
        this.animateFrames()
        }
};

//Fighter Class
class Fighter extends Sprite {
    constructor({ 
        position, 
        velocity, 
        color = 'red', 
        imageSrc, 
        scale = 1, 
        framesMax = 1,
        offset = {x: 0, y: 0},
        sprites,
        attackBox = { offset: {}, width: undefined, height: undefined},
        effectBox = { offset: {}, width: undefined, height: undefined}
    }) {
        super({
            position,
            imageSrc,
            scale,
            framesMax,
            offset
        })

        this.velocity = velocity
        this.width = 50
        this.height = 150
        this.lastKey
        this.attackBox = {
            position: {
                x: this.position.x,
                y: this.position.y
            },
            offset: attackBox.offset,
            width: attackBox.width,
            height: attackBox.height,
        }
        this.effectBox = {
            position: {
                x: this.position.x,
                y: this.position.y
            },
            offset: effectBox.offset,
            width: effectBox.width,
            height: effectBox.height,
        }
        this.color = color
        this.isAttacking
        this.health = 100
        this.framesCurrent = 0
        this.framesElapsed = 0
        this.framesHold = 20
        this.sprites = sprites

        for (const sprite in this.sprites) {
            sprites[sprite].image = new Image()
            sprites[sprite].image.src = sprites[sprite].imageSrc
        }
    }

    update() {
        this.animateFrames()
        this.draw()

        this.attackBox.position.x = this.position.x + this.attackBox.offset.x;
        this.attackBox.position.y = this.position.y + this.attackBox.offset.y;
        
/*        c.fillRect(this.attackBox.position.x,
                    this.attackBox.position.y,
                    this.attackBox.width,
                    this.attackBox.height)
*/

        this.position.x += this.velocity.x
        this.position.y += this.velocity.y

        if (this.position.y + this.height + this.velocity.y >= canvas.height - 25) {
            this.velocity.y = 0
            this.position.y = 401.1
        } else this.velocity.y += gravity
    }
    
    attack() {
        this.switchSprite('attack1')
        this.isAttacking = true;
    }

    hurt() {
        this.switchSprite('hurt')
        this.health -= 20
    }

    switchSprite(sprite) {
        if (this.image === this.sprites.attack1.image 
            && this.framesCurrent < this.sprites.attack1.framesMax - 1) return
        switch (sprite) {
            case 'idle':
                if (this.image !== this.sprites.idle.image) {
                    this.image = this.sprites.idle.image
                    this.framesMax = this.sprites.idle.framesMax
                    this.framesCurrent = 0
                }
                break
            case 'run':
                if (this.image !== this.sprites.run.image) {
                    this.image = this.sprites.run.image
                    this.framesMax = this.sprites.run.framesMax
                    this.framesCurrent = 0
                }
                break
            case 'jump':
                if (this.image !== this.sprites.jump.image) {
                    this.image = this.sprites.jump.image
                    this.framesMax = this.sprites.jump.framesMax
                    this.framesCurrent = 0
                }
                break
            case 'attack1':
                if (this.image !== this.sprites.attack1.image) {
                    this.image = this.sprites.attack1.image
                    this.framesMax = this.sprites.attack1.framesMax
                    this.framesCurrent = 0
                }
                break
            case 'hurt':
                if (this.image !== this.sprites.hurt.image) {
                    this.image = this.sprites.hurt.image
                    this.framesMax = this.sprites.hurt.framesMax
                    this.framesCurrent = 0
                }
                break
        }
    }
};

const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')

canvas.width = 1024;
canvas.height = 576;

c.fillRect(0, 0, canvas.width, canvas.height);

const gravity = 0.3;

const background0 = new Sprite ({
    position: {
        x: 0,
        y: 0
    },
    imageSrc: "./img/backgrounds/0.png",
});

const background1 = new Sprite ({
    position: {
        x: 0,
        y: 540
    },
    imageSrc: "./img/backgrounds/1.5.png",
});

const pineTree = new Sprite ({
    position: {
        x: 700,
        y: 360
    },
    imageSrc: "./img/backAnimation/Pine Tree - Medium Snow  - Spritesheet.png",
    scale: 2,
    framesMax: 41,
});

const slimSpruce = new Sprite ({
    position: {
        x: 350,
        y: 412
    },
    imageSrc: "./img/backAnimation/Slim Spruce Tree - High Snow - Spritesheet.png",
    scale: 1.5,
    framesMax: 41,
});


/* Player */
const player = new Fighter({
    position: {
        x: 0,
        y: 0
    },
    velocity: {
        x: 0,
        y: 0    
    },
    offset: {
        x: 0,
        y: 0
    },
    imageSrc: "./img/fighters/Homeless_1/Idle_2.png",
    framesMax: 11,
    scale: 1.7,
    offset: {
        x: -100,
        y: 60
    },
    sprites: {
        idle: {
            imageSrc: "./img/fighters/Homeless_1/Idle_2.png",
            framesMax: 11,
        },
        run: {
            imageSrc: "./img/fighters/Homeless_1/walk.png",
            framesMax: 8,
        },
        jump: {
            imageSrc: "./img/fighters/Homeless_1/Jump.png",
            framesMax: 16,
        },
        attack1: {
            imageSrc: "./img/fighters/Homeless_1/Attack_1.png",
            framesMax: 5,
        },
    },
    attackBox: {
        offset: {
            x: 215,
            y: 65
        },
        width: 48,
        height: 50,
    },
});


/* Enemy */
const enemy = new Fighter({
    position: {
        x: 824,
        y: 250
    },
    velocity: {
        x: 0,
        y: 0    
    },
    offset: {
        x: -50,
        y: 0
    },
    color: 'blue',
    imageSrc: "./img/fighters/Homeless_2/Idle_2.png",
    framesMax: 9,
    scale: 1.7,
    offset: {
        x: 100,
        y: 60
    },
    sprites: {
        idle: {
            imageSrc: "./img/fighters/Homeless_2/Idle.png",
            framesMax: 7,
        },
        run: {
            imageSrc: "./img/fighters/Homeless_2/walk.png",
            framesMax: 8,
        },
        jump: {
            imageSrc: "./img/fighters/Homeless_2/Jump.png",
            framesMax: 12,
        },
        attack1: {
            imageSrc: "./img/fighters/Homeless_2/Attack_2.png",
            framesMax: 4,
        },
        hurt: {
            imageSrc: "./img/fighters/Homeless_2/Hurt.png",
            framesMax: 3
        },
    },
    attackBox: {
        offset: {
            x: -59,
            y: 65
        },
        width: 48,
        height: 50,
    },
});

/* Keys Object */
const keys = {
    a: {
        pressed: false
    },
    d: {
        pressed: false
    },
    w: {
        pressed: false
    },
    ArrowLeft: {
        pressed: false
    },
    ArrowRight: {
        pressed: false
    },
    ArrowUp: {
        pressed: false
    }
}

decreaseTimer();

/* Animation Loop */
function animate() {
    window.requestAnimationFrame(animate);
    c.fillStyle = 'black'
    c.fillRect(0, 0, canvas.width, canvas.height)
    background0.update()
    pineTree.update()
    slimSpruce.update()
    player.update()
    enemy.update()
    background1.update()

    player.velocity.x = 0
    enemy.velocity.x = 0

    // Player Movement
    if (keys.a.pressed && player.lastKey === 'a') {
        player.velocity.x = -2
        player.switchSprite('run')
    } else if (keys.d.pressed && player.lastKey === 'd') {
        player.velocity.x = 2
        player.switchSprite('run')
    } else {
        player.switchSprite('idle')
    }

    if (player.velocity.y < 0) {
        player.switchSprite('jump')
    }

    // Enemy Movement
    if (keys.ArrowLeft.pressed && enemy.lastKey === 'ArrowLeft') {
        enemy.velocity.x = -2
        enemy.switchSprite("run")
    } else if (keys.ArrowRight.pressed && enemy.lastKey === 'ArrowRight') {
        enemy.velocity.x = 2
        enemy.switchSprite("run")
    } else {
        enemy.switchSprite("idle")
    }

    if (enemy.velocity.y < 0) {
        enemy.switchSprite('jump')
    }

    // detect for collision player to enemy
    if (
        rectangularCollision({
        rectangle1: player,
        rectangle2: enemy
        }) && 
        player.isAttacking && 
        player.framesCurrent === 1
    ) {
        console.log("hit")
        enemy.hurt()
        player.isAttacking = false
        document.querySelector('#enemyHealth').style.width = enemy.health + "%";
    }  
    
    //if player misses hit
    if (player.isAttacking && player.framesCurrent === 1) {
        player.isAttacking = false
    }

    // detect for collision enemy to player
    if (
        rectangularCollision({
        rectangle1: enemy,
        rectangle2: player
        }) && 
        enemy.isAttacking && 
        enemy.framesCurrent === 1
    ) {
        console.log("hit")
        player.hurt()
        enemy.isAttacking = false
        document.querySelector('#playerHealth').style.width = enemy.health + "%";
    }  
    
    //if player misses hit
    if (enemy.isAttacking && enemy.framesCurrent === 1) {
        enemy.isAttacking = false
    }

    if (enemy.health <= 0 || player.health <= 0) {
        determineWinner({ player, enemy, timerId })
    }
}

animate();

/* Event Listeners for Controls */
window.addEventListener('keydown', (event) => {
    switch (event.key) {

    /* Player Controls */
        case 'd':
            keys.d.pressed = true;
            player.lastKey = 'd';
            break
        case 'a':
            keys.a.pressed = true;
            player.lastKey = 'a';
            break  
        case 'w':
            player.velocity.y = -13;
            break
        case 'f':
            player.attack()
            break

    /* Enemy Controls */
        case 'ArrowRight':
            keys.ArrowRight.pressed = true;
            enemy.lastKey = 'ArrowRight';
            break
        case 'ArrowLeft':
            keys.ArrowLeft.pressed = true;
            enemy.lastKey = 'ArrowLeft';
            break  
        case 'ArrowUp':
            enemy.velocity.y = -13;
            break
        case 'Control':
            enemy.attack()
            break
    }
});

/* Event Listeners for Controls on "Release" */
window.addEventListener('keyup', (event) => {
    switch (event.key) {

    /* Player Controls */
        case 'd':
            keys.d.pressed = false;
            break    
        case 'a':
            keys.a.pressed = false;
            break 
        case 'w':
            keys.w.pressed = false;
            break

    /* Enemy Controls */
        case 'ArrowRight':
            keys.ArrowRight.pressed = false;
            break    
        case 'ArrowLeft':
            keys.ArrowLeft.pressed = false;
            break 
        case 'ArrowUp':
            keys.ArrowUp.pressed = false;
            break
    }
});

I can’t seem to find what is different in the attack code and collision detection for player 2 vs player 1.

how to solve the cors error in vue js while loading js component to html

cant import counter.js file to index.html. white screen output and console log shows cors error

tried to program a couner.js file and import it to the index.html and all it shows is a white screen
my index.html is shown as follows

<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app"></div>
</body>
<script type="module">
import Counter from "./Counter.js";    //tried all variations of small and large case in filename  and "../Counter.js" too //
var app = Vue.createApp({
components : {
Counter:Counter
},
template : "<Counter/>"
});
var vm = app.mount("div#app");
</script>
</html>

and my counter.js file is

const Counter = {
data() {
return {
count: 0
}
},
template : "The counter is: {{count}}",
created() {
setInterval(() => {
this.count += 1;
}, 1000)
}
}
export default Counter;

both are saved in the same folder
the result expected was an infinity counter but what i got is a blank screen and a console log “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/hp/Desktop/Counter.js. (Reason: CORS request not http)”
if creating a local host server is the answer then show me how to as you would show it to a beginner

How to append an element to another rotated and positioned element while maintaining its position on the screen?

I have the following HTML structure:

codepen

<body>
<button onclick={appendBlueToGreen()}>Append To Green</button>
  <div id="red" style="transform: rotate(20deg); width: 100px; height: 100px; position: absolute; top: 50px; left: 50px; background-color: red;">
    <div id="green" style="transform: rotate(20deg); width: 80px; height: 80px; position: absolute; top: 13px; left: 11px; background-color: green;">
    </div>
  </div>
  <div id="blue" style="transform: rotate(45deg); width: 50px; height: 50px; position: absolute; top: 29px; left: 313px; background-color: blue;"></div>
</body>

I want to append the #blue element to the #green element, but the #blue element should maintain its exact position on the screen. In other words, the #blue element should be a child of the #green element, but its visual position and rotation should remain unchanged. So whether the #blue element is attached to #green, <body>, or any other element, it should remain in the same position as in the image below.

enter image description here

To achieve this, I need to:

  • Calculate the absolute position and rotation of the #green and #red elements
    relative to the document body.
  • Adjust the position and rotation of the #blue element based on the
    calculated position and rotation of the #red and #green element, so that it
    appears at the same position on the screen but within the #green
    element.
  • Counter-rotate the #blue element to negate the effect of the
    rotations applied to the #green and #red elements.

I’m struggling to figure out the correct mathematical calculations to achieve this. I would greatly appreciate if someone could provide a JavaScript solution to achive this.

Here is the code that I have used with the help of AI to achieve this, but it was not successful:
codepen

Javascript call scrollIntoView on scroll

I woudl like to trigger scrollIntoView on mouse wheel scroll. This works when I click a button, but it seems while on scroll its not (even if I restrict it to just happenning one like in example below)

document.getElementById('next').addEventListener('click', function() {

  var target = document.getElementById('target')
  target.scrollIntoView({
    behavior: "smooth",
    block: 'nearest'
  });
})

var scrollActive

window.addEventListener("wheel", event => {



  const delta = Math.sign(event.deltaY);


  if (!scrollActive) {

    scrollActive = true;

    if (delta == 1) {

      console.info(delta);

      var target = document.getElementById('target')
      target.scrollIntoView({
        behavior: "smooth",
        block: 'nearest'
      });

    }

  }


});
.a {
  width: 50px;
  height: 250px;
  border: 1px solid #444;
  margin: 20px;
}
<a id="next" href="#">play next</a>

<div class="a">1</div>
<div class="a">2</div>
<div class="a">3</div>
<div class="a">4</div>
<div class="a" id="target">5</div>
<div class="a">6</div>
<div class="a">7</div>