Collision Detection in JavaScript for a ball and square

I am attempting to recreate a mobile app called ballz within javascript. This is my first project so I apologize if it hurts your head to read through it.

The ball is shot using the mouse to determine its velocity.
The ball should continually check for collision with a static block.
Depending on if the ball hits a corner or side of the block, the velocity is calculated using the code I provided.

The issue is that the collision response is all over the place. Sometimes the sideCollisionReponse works flawlessly, sometimes the cornerCollisionResponse works flawlessly. However, most of the time, the ball clips through blocks, reflects sporadically, or a combination of the two.

document.addEventListener('DOMContentLoaded', function() {
    const canvas = document.querySelector('canvas');
    const c = canvas.getContext("2d");

    canvas.width = 360;
    canvas.height = 600;
    let isDragging = false;
    let aimX = 0;
    let aimY = 0;

    function drawPoints(points) {
        c.font = '24px Arial';
        c.fillStyle = 'white';
        c.textAlign = 'center';
        c.fillText('Points: ' + points, canvas.width / 2, 30);
    }

    class Sprite {
        constructor(position) {
            this.position = position;
            this.velocity = {
                x: 0,
                y: 0
            };
            this.isShooting = false;
            this.isStuck = false;
            this.points = 0;
            this.radius = 10;
        }

        // May be able to optimize by defining the ball size into a variable for size specific calls
        draw() {
            c.beginPath();
            c.arc(this.position.x, this.position.y, 10, 0, 2 * Math.PI);
            c.fillStyle = "orange";
            c.fill();
        }

        checkCollision() {

            this.wallsCollisionResponse();

            for (let i = 0; i < blocks.length; i++) {
                let block = blocks[i];
                const topLeftDist = Math.sqrt((this.position.x - block.x) ** 2 + (this.position.y - block.y) ** 2);
                const topRightDist = Math.sqrt((this.position.x - block.x - block.width) ** 2 + (this.position.y - block.y) ** 2);
                const bottomLeftDist = Math.sqrt((this.position.x - block.x) ** 2 + (this.position.y - block.y - block.height) ** 2);
                const bottomRightDist = Math.sqrt((this.position.x - block.x - block.width) ** 2 + (this.position.y - block.y - block.height) ** 2);
                const isCornerCollision = (topLeftDist <= this.radius || topRightDist <= this.radius || bottomLeftDist <= this.radius || bottomRightDist <= this.radius)

                if (!isCornerCollision) {
                    this.sidesCollisionResponse(block);
                } else if (isCornerCollision) {
                    this.cornerCollisionResponse(block);
                }
            }
        };

        wallsCollisionResponse() {
            let x = this.position.x
            let y = this.position.y

            // Check collision with walls
            if (x - this.radius <= 0 || x + this.radius >= canvas.width) {
                this.velocity.x = -this.velocity.x; // Reverse horizontal velocity
                this.position.x = Math.max(this.radius, Math.min(canvas.width - this.radius, x)); // Limit position within bounds
            }
            if (y - this.radius <= 40 || y + this.radius >= canvas.height) {
                this.velocity.y = -this.velocity.y; // Reverse vertical velocity
                this.position.y = Math.max(this.radius + 40, Math.min(canvas.height - this.radius, y)); // Limit position within bounds
            }

            // Check if ball hits bottom
            if (y + this.radius >= canvas.height) {
                this.isStuck = true;
                this.velocity = {
                    x: 0,
                    y: 0
                };
            }
        }


        cornerCollisionResponse(block) {
            // get line from ball center to corner
            const v1x = this.position.x - block.x
            const v1y = this.position.y - block.y;

            // normalize the line and rotated 90deg to get tanget
            const len = (v1x ** 2 + v1y ** 2) ** 0.5;
            const tx = -v1y / len;
            const ty = v1x / len;

            const dot = (this.velocity.x * tx + this.velocity.y * ty) * 2;

            this.velocity.x = -this.velocity.x + tx * dot;
            this.velocity.y = -this.velocity.y + ty * dot;

            block.decreaseValue();
        }


        sidesCollisionResponse(block) {
            let x = this.position.x
            let y = this.position.y
            let maxSpeed = 20;
            if (
                block.x + block.width >= x - this.radius &&
                block.x <= x + this.radius &&
                block.y + block.height >= y - this.radius &&
                block.y <= y + this.radius
            ) {
                // Calculate collision normal (assuming block is axis-aligned)
                let normalX = 0;
                let normalY = 0;
                if (x < block.x) {
                    normalX = -1; // Collision from left
                } else if (x > block.x + block.width) {
                    normalX = 1; // Collision from right
                }
                if (y < block.y) {
                    normalY = -1; // Collision from top
                } else if (y > block.y + block.height) {
                    normalY = 1; // Collision from bottom
                }

                console.log('Initial velocity1:', this.velocity);

                // Reflect velocity using dot product with normal vector
                let dotProduct = this.velocity.x * normalX + this.velocity.y * normalY;
                this.velocity.x -= 2 * dotProduct * normalX;
                this.velocity.y -= 2 * dotProduct * normalY;

                console.log('Initial velocity2:', this.velocity);

                // Limit velocity to maxSpeed
                const currentSpeed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y);
                if (currentSpeed > maxSpeed) {
                    const ratio = maxSpeed / currentSpeed;
                    this.velocity.x *= ratio;
                    this.velocity.y *= ratio;
                }

                this.limitVelocity();

                // Adjust position to prevent clipping
                const overlapX = Math.abs(x - block.x - block.width);
                const overlapY = Math.abs(y - block.y - block.height);
                const separationX = overlapX * normalX;
                const separationY = overlapY * normalY;
                //this.position.x += separationX;
                //this.position.y += separationY;

                block.decreaseValue();
            }
        }


        limitVelocity() {
            // Limit velocity to maxSpeed
            const maxValue = 20;
            if (this.velocity.x > maxValue) {
                this.velocity.x = maxValue;
            } else if (this.velocity.x < -maxValue) {
                this.velocity.x = -maxValue
            }
            if (this.velocity.y > maxValue) {
                this.velocity.y = maxValue;
            } else if (this.velocity.y < -maxValue) {
                this.velocity.y = -maxValue
            }
        }


        update() {
            if (this.isShooting && !this.isStuck) {
                this.move();
                this.checkCollision();
            }
        }

        move() {
            this.position.x += this.velocity.x;
            this.position.y += this.velocity.y;
            // Simulate gravity
            // this.velocity.y += 0.2;
        }


        shoot(mouseX, mouseY) {
            // Calculate direction vector from ball to mouse
            const dx = mouseX - this.position.x;
            const dy = mouseY - this.position.y;
            const magnitude = Math.sqrt(dx * dx + dy * dy);

            const maxSpeed = 20; // Maximum speed limit

            if (magnitude !== 0) {
                const normalizedDx = dx / magnitude;
                const normalizedDy = dy / magnitude;
                const speed = Math.min(magnitude, maxSpeed); // Limit speed to maximum speed
                this.velocity.x = normalizedDx * speed;
                this.velocity.y = normalizedDy * speed;
            }
            this.isShooting = true;
        }


        reset(position) {
            this.position = position; // Maintains last position on reset
            this.velocity = {
                x: 0,
                y: 0
            };
            this.isShooting = false; // this may be unneccessary
            this.isStuck = false;
        }

        getPoints() {
            this.points++;
            return this.points;
        }
    }
    const player = new Sprite({
        x: 180,
        y: 590
    });


    class Block {
        constructor(x, y, width, height, value) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.value = value + 1;
        }

        draw() {
            c.fillStyle = 'green';
            c.fillRect(this.x, this.y, this.width, this.height);
            // Text
            c.fillStyle = 'white';
            c.font = '12px Arial'; // Adjust the font size and style as needed
            c.fillText(this.value.toString(), this.x + this.width / 2, this.y + this.height / 1.75);
        }

        decreaseValue() {
            if (this.value > 0) {
                this.value - 1;
                if (this.value === 0) {
                    // Remove block if value reaches 0
                    blocks.splice(blocks.indexOf(this), 1);
                }
            }
        }

        shiftDown() {
            this.y += this.height + 6
        }
    }
    const blocks = [];

    function createBlocks() {
        const blockWidth = 40;
        const blockHeight = 40;
        const numBlocks = 1;
        //Math.floor(canvas.width / blockWidth);

        for (let i = 0; i < numBlocks; i++) {
            const blockValue = player.points;
            blocks.push(new Block(120, 80, blockWidth, blockHeight, blockValue));
        }
    }

    createBlocks();

    function animate() {
        requestAnimationFrame(animate); // clears canvas before next frame
        c.clearRect(0, 0, canvas.width, canvas.height);
        c.fillStyle = '#4D4D4D'; // Top bar color
        c.fillRect(0, 0, canvas.width, 40);


        if (isDragging && !player.isShooting) {
            const dx = aimX - player.position.x;
            const dy = aimY - player.position.y;
            const magnitude = Math.sqrt(dx * dx + dy * dy);
            const maxSegments = 20; // Maximum number of segments
            const totalTime = 1; // Total time for preview (adjust as needed)

            for (let i = 0; i < maxSegments; i++) {
                const progress = i / maxSegments; // Progress along the trajectory
                const time = progress * totalTime; // Time at this segment
                const previewX = player.position.x + dx * time;
                const previewY = player.position.y + dy * time; // Vertical motion with gravity + 0.5 * 9.81 * time * time
                c.beginPath();
                c.arc(previewX, previewY, player.radius, 0, 2 * Math.PI);
                const alpha = 1 - i * (0.5 / maxSegments); // Decrease transparency for each segment
                c.fillStyle = `rgba(255, 165, 0, ${alpha})`; // Transparent orange
                c.fill();
            }
        }


        player.draw();
        player.update();

        drawPoints(player.points);

        blocks.forEach((block, index) => {
            block.draw();
        });

        if (player.isStuck) {
            player.reset({
                x: player.position.x,
                y: player.position.y
            })
            player.getPoints();
            blocks.forEach((block, index) => {
                block.shiftDown();
            })
            createBlocks();

        }
    }

    animate();

    canvas.addEventListener("mousedown", (event) => {
        const rect = canvas.getBoundingClientRect();
        const mouseX = event.clientX - rect.left;
        const mouseY = event.clientY - rect.top;

        if (!player.isShooting && mouseX >= 0 && mouseX <= canvas.width && mouseY >= 0 && mouseY <= canvas.height - 20) {
            isDragging = true;
            aimX = mouseX;
            aimY = mouseY;
        }
    })

    canvas.addEventListener("mouseup", (event) => {
        if (isDragging) {
            isDragging = false;
            const rect = canvas.getBoundingClientRect();
            const mouseX = event.clientX - rect.left;
            const mouseY = event.clientY - rect.top;
            if (mouseX >= 0 && mouseX <= canvas.width && mouseY >= 0 && mouseY <= canvas.height - 20) {
                player.shoot(aimX, aimY); // Pass aim position to shoot method
            }
        }
    })

    canvas.addEventListener("mousemove", (event) => {
        if (isDragging) {
            const rect = canvas.getBoundingClientRect();
            aimX = event.clientX - rect.left;
            aimY = event.clientY - rect.top;
        }
    })
});

Stolen characters in the variable

`
let text = ‘hello world’,
missingText = ‘helo word’;// Here is a “l”;

function theMissingText () {

return missingLetter;

}

// If the variable contains a missing character, it returns the leading character
// If it has no missing character, it returns -1

// How to return this character in any variable, regardless of where it is in the text, Example:


let $_text = "original text",
    $_missingText = 'original ext'; // here is "t"

// & here is 

let $_text_2 = "original text",
    $_missingText_2 = 'orignal text'; // here is "i";
`

What files are needed to create a successful front and back end of webpage?

I am getting started in my journey to becoming a developer and I wanted more clarity on certain things when building websites in relation to the front end and the backend.

For example is Javascript in the front end built in a different .js file to the backend on the server side?

Also I am currently learning about EJS and based on the information I have seen, does this replace HTML? or do they kind of work together to build more dynamic webpages?

Any help would be appreciated 🙂

as per the above, I just need more information on front end and back end

How to ensure html2canvas snapshots are within x and y coordinates?

I have a simple React component for testing, it has an initial rectangle which can be move and reshaped, I also have a button on the screen which is supposed to allow me to take a snapshot of the Body within the rectangle but at the moment, the snapshot seems to be misaligned?


import React from "react";
import html2canvas from "html2canvas";

function TestPlayground() {
  const defaultPosition = {
    startX: 1036,
    startY: 470,
    endX: 511,
    endY: 170,
  };

  const [state, setState] = React.useState({
    startX: defaultPosition.startX,
    startY: defaultPosition.startY,
    endX: defaultPosition.endX,
    endY: defaultPosition.endY,
    isDragging: false,
    isResizing: false,
    offsetX: 0,
    offsetY: 0,
    resizeHandle: "",
  });

  const width = Math.abs(state.endX - state.startX);
  const height = Math.abs(state.endY - state.startY);
  const left = Math.min(state.startX, state.endX);
  const top = Math.min(state.startY, state.endY);

  function handleMouseDown(e) {
    const { clientX, clientY } = e;
    const resizeHandle = getResizeHandle(clientX, clientY);

    if (resizeHandle) {
      setState((prevState) => ({
        ...prevState,
        isResizing: true,
        offsetX: clientX - state.endX,
        offsetY: clientY - state.endY,
        resizeHandle: resizeHandle,
      }));
    } else {
      setState((prevState) => ({
        ...prevState,
        isDragging: true,
        offsetX: clientX - left,
        offsetY: clientY - top,
      }));
    }
  }

  function handleMouseUp() {
    setState((prevState) => ({
      ...prevState,
      isDragging: false,
      isResizing: false,
      resizeHandle: "",
    }));
  }

  function handleMouseMove(e) {
    const { clientX, clientY } = e;

    if (state.isDragging) {
      const newStartX = clientX - state.offsetX;
      const newStartY = clientY - state.offsetY;
      setState((prevState) => ({
        ...prevState,
        startX: newStartX,
        startY: newStartY,
        endX: newStartX + width,
        endY: newStartY + height,
      }));
    } else if (state.isResizing) {
      const newEndX = clientX - state.offsetX;
      const newEndY = clientY - state.offsetY;
      setState((prevState) => ({
        ...prevState,
        endX: newEndX,
        endY: newEndY,
      }));
    }
  }

  function getResizeHandle(clientX, clientY) {
    const handleSize = 10;

    const handlePositions = {
      nw: { x: left, y: top },
      ne: { x: left + width, y: top },
      sw: { x: left, y: top + height },
      se: { x: left + width, y: top + height },
    };

    for (let handle in handlePositions) {
      const { x, y } = handlePositions[handle];
      if (
        clientX >= x - handleSize &&
        clientX <= x &&
        clientY >= y - handleSize &&
        clientY <= y
      ) {
        return handle;
      }
    }

    return null;
  }

  const takeSnapShot = () => {
    const body = document.querySelector("body");

    if (body) {
      html2canvas(body).then((canvas) => {
        const croppedCanvas = document.createElement("canvas");
        const croppedCanvasContext = croppedCanvas.getContext("2d");

        const width = Math.abs(state.endX - state.startX);
        const height = Math.abs(state.endY - state.startY);
        const left = Math.min(state.startX, state.endX);
        const top = Math.min(state.startY, state.endY);

        croppedCanvas.width = width;
        croppedCanvas.height = height;

        if (croppedCanvasContext) {
          // Draw the cropped region onto the new canvas
          croppedCanvasContext.drawImage(
            canvas,
            top, // sx: x-axis coordinate of the top-left corner of the sub-rectangle
            left, // sy: y-axis coordinate of the top-left corner of the sub-rectangle
            width, // sWidth: width of the sub-rectangle to draw
            height, // sHeight: height of the sub-rectangle to draw
            0, // dx: x-axis coordinate in the destination canvas to place the top-left corner of the source image
            0, // dy: y-axis coordinate in the destination canvas to place the top-left corner of the source image
            width, // dWidth: width to draw the image in the destination canvas (optional, will default to sWidth)
            height // dHeight: height to draw the image in the destination canvas (optional, will default to sHeight)
          );
        }

        const imageData = croppedCanvas.toDataURL("image/jpeg");
        console.log(imageData);
      });
    }
  };

  return (
    <div>
      <div
        onMouseDown={handleMouseDown}
        onMouseUp={handleMouseUp}
        onMouseMove={handleMouseMove}
        style={{
          position: "absolute",
          left: `${left}px`,
          top: `${top}px`,
          width: `${width}px`,
          height: `${height}px`,
          border: "2px dotted black",
          zIndex: "99",
          backgroundColor: "rgba(0, 0, 0, 0)", // Transparent background
          cursor: state.isDragging || state.isResizing ? "grabbing" : "grab",
          resize: "both",
          overflow: "auto",
        }}
      />
      <div>
        <div style={{ display: "flex", width: 1000 }}>
          <div
            style={{
              backgroundColor: "red",
              width: 500,
              height: 200,
              alignSelf: "end",
            }}
          />
        </div>
        <button onClick={() => takeSnapShot()}>TAKE SNAPSNOT</button>
      </div>
    </div>
  );
}

export default TestPlayground;

Is my top and left value off? am I missing something here?

Thanks for the help.

Read more button deactivates

The read more button deactivates when i make another one in another paragraph but as long as i make 2 or 3 read more button at the same paragraph it works. I want all the buttons activated how can i fix this problem ?

const parentContainer = document.querySelector('.read-more-container');
parentContainer.addEventListener('click', event => {
  const current = event.target;
  const isReadMoreBtn = current.className.includes('read-more-btn');
  if (!isReadMoreBtn) return;
  const currentText = event.target.parentNode.querySelector('.read-more-text');
  currentText.classList.toggle('read-more-text--show');
  current.textContent = current.textContent.includes('Read More') ? "Read Less..." : "Read More...";
})
<div class="read-more-container">
  <div class="container">
    <p>
      Lorem ipsum dolor sit, amet consectetur adipisicing elit. Unde, facere? Quae distinctio reprehenderit soluta fugiat, alias, doloremque similique tenetur magni voluptate a, perspiciatis quaerat! Necessitatibus velit consectetur expedita consequatur assumenda!
      <span class="read-more-text">
                                             Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quasi quaerat, amet explicabo magnam, nulla porro dolorem itaque
                                         </span>
    </p>
    <span class="read-more-btn">Read More...</span>
  </div>
  <div class="container">
    <p>
      Lorem ipsum dolor sit, amet consectetur adipisicing elit. Unde, facere? Quae distinctio reprehenderit soluta fugiat, alias, doloremque similique tenetur magni voluptate a, perspiciatis quaerat! Necessitatibus velit consectetur expedita consequatur assumenda!
      <span class="read-more-text">
                                             Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quasi quaerat, amet explicabo magnam, nulla porro dolorem itaque
                                         </span>
    </p>
    <span class="read-more-btn">Read More...</span>
  </div>
</div>
<div class="card-courses-list admin-courses">
</div>
<div class="card-courses-full-dec">
  <div class="card-courses-title">
    <h4></h4>
  </div>
  <div class="card-courses-list-bx">
    <ul class="card-courses-view">
      <li class="card-courses-user">
        <div class="card-courses-user-pic">
        </div>
        <div class="card-courses-user-info">
          <h5>Client</h5>
          <h4>Khaled Ahmed Yasser</h4>
        </div>
      </li>
      <li class="card-courses-user-info">
        <h5>Request Date</h5>
        <h4>28/02/2024</h4>
      </li>
      <li class="card-courses-user-info">
        <h5>Total Meals</h5>
        <h4>15</h4>
      </li>
      <li class="card-courses-price">
        <del></del>
        <h5 class="text-primary"></h5>
      </li>
    </ul>
  </div>
  <div class="row card-courses-dec">
    <div class="col-md-12">
      <h6 class="m-b10">Request details</h6>
      <p>Start Date: 29/02/2024
        <div style="white-space: pre-wrap;"></div>
        <p>End Date: 15/03/2024 </p>
        <p>City: Nasr City</p>
        <p>Address: 8th district 9 Al zomor street </p>
    </div>
    <div class="col-md-12">
      <a href="#" class="btn gray outline radius-xl ">View Meals Details</a>
    </div>
  </div>
  <div class="read-more-container0">
    <div class="container">
      <p>
        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Unde, facere? Quae distinctio reprehenderit soluta fugiat, alias, doloremque similique tenetur magni voluptate a, perspiciatis quaerat! Necessitatibus velit consectetur expedita consequatur assumenda!
        <span class="read-more-text">
                        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quasi quaerat, amet explicabo magnam, nulla porro dolorem itaque
                    </span>
      </p>
      <span class="read-more-btn">Read More...</span>
    </div>
    <div class="container">
      <p>
        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Unde, facere? Quae distinctio reprehenderit soluta fugiat, alias, doloremque similique tenetur magni voluptate a, perspiciatis quaerat! Necessitatibus velit consectetur expedita consequatur assumenda!
        <span class="read-more-text">
                        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quasi quaerat, amet explicabo magnam, nulla porro dolorem itaque
                    </span>
      </p>
      <span class="read-more-btn">Read More...</span>
    </div>
  </div>

(javascript object) if the next values greater of first value by 1 add the values in new object, if not, ignore the values

I have an object and a variable that represents 1 as a value. It can be more, for example: 1,2,3,4,5.....etc.

What I want is to compare the following values with the first value in the object, and if the result of subtracting the first value is greater than or equal to 1, add these values to a new object.
For example:
The first value is 10. The next value is 10.5, which is the largest of 10. We subtract 10 from 10.5. The result is 0.5. This result is less than 1, so we ignore it.

We move to the next value, which is 11, and since 11 is greater than 10.5, we subtract 10 from 11 and not 10.5 from 11. The result is 1, we add it in the new object, and the result is like this: {pr:10, pr:11}.

We move to the next value, which is 11.3, and since 11.3 is greater than 11, we subtract 10from 11.3. The result is 1.3, and now we add it to the new object, and the result is like this: {pr:10, pr:11, pr:11.3}.

We move to the next value, which is 12, which is larger than the previous value, 11.3. we subtract 10 from 12. The result is 2, and now we add it to the new object, and the result is like this: {pr:10, pr:11, pr:11.3, pr:12 }.

We move to the next value, which is 11.5, and we notice that this value is smaller than the previous value, 12. Therefore, we do not subtract 11.5 from 10, but from the previous value, which is 12, and the result is 0.5, so we do not add it to the new object.

We move to the next value, which is 12, and since the previous value was not added to the new object, we compare it with the value that was before 11.5, which is 12, and since the values are equal, we do not add anything to the new object.
So the new object remains as it is.{pr:10, pr:11, pr:11.3, pr:12}.

We move to the next value, which is 11, and since 11 is less than 12, we subtract 11 from 12, and the result is 1, so we add 11 to the new object. The result is: {pr:10, pr:11, pr:11.3, pr:12, pr:11}.

I spent a lot of time trying to reach a conclusion but I couldn’t.
Anyone who can help me, I appreciate this, and thanks to everyone.

let lists = [
  { id: "1", price: 10,  },
  { id: "2", price: 10.5 },
  { id: "3", price: 11,  },
  { id: "4", price: 11.3,},
  { id: "5", price: 12,  },
  { id: "6", price: 11.5 },
  { id: "7", price: 12,  },
  { id: "8", price: 11,  },
]
let finalList = [
  { id: "1", price: 10,  },
  { id: "3", price: 11,  },
  { id: "4", price: 11.3,},
  { id: "5", price: 12,  },
  { id: "8", price: 11,  },
]

JS append malfunction

I’m trying to make a page where you type in a url and it opens the url, but then appends the page content to the tab. So far my js code is this:

<script>
    var url = "<?php echo $_GET['url']; ?>";
    var tab = window.open(url, "_blank");
    tab.appendChild("<?php echo file_get_contents($_GET['url']); ?>");
</script>

Based on what I understand, it should open the requested page, then append the code to the page. Any help would be much appreciated, thank you.

How to make sure a page only available for a period of time

I’m doing a project recording the attendance of the students using html, php and js. The students should not be able to record their attendance after some time.

I’m struggling to find a way to make sure the page that records the attendance should not be available after the set time. The period should be a user input. Hope I’ll be assisted on this. Thanks

JS generate subset of array with given number and slide count

I’m working on creating customized slider in reactJS for which I’m creating a function to generated expected output and this functions takes sliderItems(holds array list), slider count(variable name ‘spliceCount’) and with how many items it should slide(variable name ‘slideBy’).

let say I have a function which takes the three attributes like array, splice-count and slideBy and return me the subsets of array based on splice-count and slideby.
As of now with below function I’m able to generate the output as shown in below snippet.

const list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'];
const spliceCount = 3;
const slideBy = 2;
function getSusetofArray(array, splice, slide) {
  const arrayList = [...array];
  const subsetList = [];
   while(arrayList > 0) {
    subsetList.push(arrayList.splice(0, splice));
  }
  return subsetList;
}
console.log(getSusetofArray(list, spliceCount, slideBy));
// current output with above function
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'], ['J', 'K']]

However, the expect out with the help of spliceCount and slideBy is needs to be like below one

expected output = [['A', 'B', 'C'], ['C', 'D', 'E'], ['E', 'F', 'G'], ['G', 'H', 'I'], ['I', 'J', 'K'], ['K']]

How to display the fetched data from the api on svelte?

first time i’m trying to write an app on svelte, i wrote the function to get the data from api and destructured the data to get only what i need. But i don’t get how to render it?

the function looks like this:

<script>
    async function getCurrencies() {
    const response = await fetch(BASE_URL);
    const data = await response.json();
    console.log(data);
    const { conversion_rates } = data;
    console.log(conversion_rates);
  }

getCurrencies();
</script>

and the element where i should render the information looks like this:

<div class="currency-input">
  <input type="number" min="0" /> // exchange rate should be displayed
  <select>
    <option value="USD">USD</option> // now it's hardcoded but i need to display the list of currencies from the API
  </select>
</div>

the response that i see on my console it’s an object with all the currencies like this:

{ USD: 1, EUR: 0.90, ... }

Someone can give some advice how to do it? I’m a little confused,

custom email contetent how to do it?

i need help because i want the stuff that i(someone) put inserted to the div “orderinfo” to be read and sent with emailjs with the mail
i need help

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Good Food</title>
    <link rel="stylesheet" href="styl.css">
    <link rel="script" href="zamow.js">
    <script type="text/javascript"
      src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js">
</script>
<script type="text/javascript">
   (function(){
      emailjs.init("k4PLn-odXcBlho7D8");
   })();
</script>

<script type="text/javascript"
       src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js">
</script>
<script type="text/javascript">
  (function () {
     emailjs.init("k4PLn-odXcBlho7D8");
  })();
</script>
<script>
  var templateParams = {
    from_name: 'order',
    message: 'details'
  };

  emailjs.send('service_1kb880o', 'template_hrbsaqs', templateParams) 
    .then(function (response) {
      console.log('SUCCESS!', response.status, response.text);
    }, function (error) {
      console.log('FAILED...', error);
    });

    
</script>



</head>
<body>
    <div class="gora">
    <div class="logo"><img  class="logoinazwa"    src="img/burger-line-64 (1).webp" alt="burger logo"></div>
    <div class="nazwa">Good Food <br> Best Catering</div>  

        <div class="ordercontainer">

            <div class="orderinfo" contenteditable="true">
                <p class="p">Addres line 1</p>
            </div>


            <div class="orderinfo" contenteditable="true">
                <p class="p">Addres line 2</p>
            </div>

            <div class="orderinfo" contenteditable="true">
                <p class="p">What time do you wish your food to be delivered?</p>
            </div>


            <div class="orderinfo" contenteditable="true">
                <p class="p">Additional requests</p>
            </div>

            <div class="button2"><p class="p2">Order Now</p>     </div>




        </div>


    
</div>
</body>

<footer class="footer"> Contact <br> Phone number +48 123 123 132 <br> E-mail [email protected] <br> Secondary e-mail [email protected]</footer>
</html>

javascript

var templateParams = {
    name: 'order',
    notes: 'next delivery'
  };
  emailjs.send('service_1kb880o', 'template_hrbsaqs', templateParams) 
    .then(function (response) {
      console.log('SUCCESS!', response.status, response.text);
    }, function (error) {
      console.log('FAILED...', error);
    });

    
     var orderinf = document.getElementsByClassName("orderinfo").addEventListener("click", displayDate);
    element.addEventListener("click", function(){ 
        
        var templateParams = {
            name: 'order',
            notes: 'details'
          };

          emailjs.send('service_1kb880o', 'template_hrbsaqs', templateParams ,) 
            .then(function (response) {
              console.log('SUCCESS!', response.status, response.text);
            }, function (error) {
              console.log('FAILED...', error);
            });
            var text=document.getElementsByClassName("orderinfo")
            print(text)
        
        ; });

im expecting it to read the div and send its content with the mail

I NEED HELP
(i know my code is messed up its my 2nd month of learning)
[ITS IN EMAILJS]

Why the fonts of my project are applied in Development Stage, but not in Production, project made in NextJS

I’m making a test product and I’ve already finished the ui with the surprise that when I deploy it to production it doesn’t have Google Fonts applied, it’s worth emphasizing that I’m using the import method for the fonts, I share the project’s repository image without fontsimage with fonts

git repo:https://github.com/Thewoker/NextJs/tree/main/gym-ecommerce

I didn’t really try many alternatives, right now I’m trying to implement the fonts no longer by importing from Google Fonts but from a local file with the fonts already downloaded

Why my terminal got stuck when I try to install ElectronJS from npm

So I am a javascript developer. I basically build web application with javascript using fontend library like react and backend framework linke express. but I wanted to try new things something like desktop development. then I stumble upon electron.js .So I thought “Why not? I know javascript fair enough. let’s try it.” then the first thing I did try to install the electron (like a normal person) following a decent tutorial. but somehow I couldn’t install the library at all. its just stuck on the last line for hours. here is my terminal activits..

PS E:studyElectronJSimage_resizer> npm i electron
npm WARN deprecated [email protected]: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
npm WARN deprecated [email protected]: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm WARN deprecated [email protected]: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.
[##################]  reify:core-js: WARN deprecated [email protected]: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature 

I just tried to install a js library man..

React Router V6 Setup

I am working on a small e-commerce app using React.js.
While setting app the router v6, nothing is rendering. There should be a mistake in the configuring the router even in App.js or Index.js. here is a snapchot from the index.js code

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </>
);

reportWebVitals();

App.js

import React from 'react';
import Cart from './pages/Cart';
import Home from './pages/Home';
import ProductDetails from './pages/ProductDetails';
import {
  RouterProvider,
  Route,
  createBrowserRouter,
  createRoutesFromElements,
  Link
} from 'react-router-dom';

const Root = () => {
  return (
    <>
      <Link to="/">Home</Link>
    </>
  );
};

const appRouter = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<Root />}>
      <Route path="home" element={<Home />} />
      <Route path="cart" element={<Cart />} />
      <Route path="product-details" element={<ProductDetails />} />
    </Route>
  )
)

function App() {
  return <RouterProvider router={appRouter} />;
}

export default App;

Please let me know if I am missing any import in index.js or if there is any mistake in App.js.

I tried online resources, tried to import createBrowserRouter and other but it did not work.

how can i get the data without that promise wrapper [duplicate]

when i write this code:

name: async function() {
        let ranNumber = ran();
        try {
            let response = await fetch('data/names.json');
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            let data = await response.json();
            let d = data[ranNumber];
            return d
        } catch (error) {
            console.error('There was a problem fetching the data:', error);
            return null;
        }
    },

i wanna the user of my lib just write nameOFLib.name() and get the data without do promise then etc

when i do nameOFLib.name() on console log it give me that :

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "Mark"

and i just need the PromiseResult