Change background-image on hover (html-css)

The big problem is that the background image I want to change is smaller than its container, and I want to change it exactly when the mouse passes over it and not over the container. I can’t access it hovering because it is just an attribute.

I tried to use a div with a background-image, but then I can’t make the div stay in a fixed position in relation to the form, at the same time without interfering with the flow of the elements (working as a background-image). I also couldn’t make the div auto-adjust to the size of its background-image, just the opposite.

Why is this array undefined and how can I fix it?

I’m making my own class for vector arithmetic, and I’ve run into a problem.
The add function is returning that v1.arr is undefined. I’ve tried to fix it, but I can’t tell what’s even causing the problem.
Here’s my code for the Vector class:

class Vector {
  constructor(coords) {
    this.arr = coords;
    this.dim = coords.length;

    switch (this.dim) {
      case 2:
        this.x = this.arr[0];
        this.y = this.arr[1];
      case 3:
        this.x = this.arr[0];
        this.y = this.arr[1];
        this.z = this.arr[2];
      case 4:
        this.x = this.arr[0];
        this.y = this.arr[1];
        this.z = this.arr[2];
        this.w = this.arr[3];
    }
  }

  add(v1) {
    for (let i = 0; i < this.dim; i++) {
      this.arr[i] += v1.arr[i];
    }
  }

  sum(v1, v2) {
    let arr = [];
    for (let i = 0; i < this.dim; i++) {
      arr[i] = v1.arr[i] + v2.arr[i];
    }

    return new Vector(arr);
  }

  scale(s1) {
    let arr = [];
    for (let i = 0; i < this.dim; i++) {
      arr[i] = this.arr[i] * s1;
    }

    return new Vector(arr);
  }

  subtract(v1) {
    for (let i = 0; i < this.dim; i++) {
      this.arr[i] -= v1.arr[i];
    }
  }


  magnitude() {
    let sum = 0;
    for (let i = 0; i < this.dim; i++) {
      sum += this.arr[i] ** 2;
    }

    return Math.sqrt(sum);
  }

  normalize() {
    return this.scale(1 / this.magnitude());
  }


  inner(v1, v2) {
    let sum = 0;
    for (let i = 0; i < this.dim; i++) {
      sum += v1.arr[i] * v2.arr[i];
    }

    return sum;
  }

  cross(v1, v2) {
    if (dim !== 3) return error;

    let arr = [];
    arr[0] = (v1.arr[1] * v2.arr[2]) - (v1.arr[2] * v2.arr[1]);
    Here;
    s t
    arr[1] = (v1.arr[0] * v2.arr[2]) - (v1.arr[2] * v2.arr[0]);
    arr[2] = (v1.arr[0] * v2.arr[1]) - (v1.arr[1] * v2.arr[0]);

    return arr;
  }
}

I’m using the class for a physics-y gravity simulation where a little blue square falls down. There are no errors there, just in the class methods.

I’ve tried things like making the parameter for the constructor inside an array; constructor([coords]) rather than constructor(coords), and while that fixed the undefined array, it also somehow removed the functionality for calling this.x, this.y, etc.

I’ve tried making the Vector class a subclass of Array, but that made things much less customizable and more confusing, so I scrapped that idea.

It might be because I just don’t know enough about JS, but I can’t tell how to fix the problem.

Authorization with access_token bearer in websocket

I’m making a real-time chat api, in which I’m listening to messages sent with socket.io, and at the same time making a post-type request to my api to create the message within the database, however, I want add authorization with a generated access_token, which is passed through a function in the front-end of my code. The question is this, is it a bad idea to pass this access_token through the websocket event every time the front-end creates a message button for a triggered?

// returns logged in user information.

"use server";

import { SessionData } from "@/types/types";
import { getServerSession } from "next-auth";

import { api } from "../lib/api";
import { signJwtAccessToken } from "../lib/jwt";

const getUser = async () => {
  const session = await getServerSession();

  try {
    const data: SessionData = session;
    const login = data.user.email;
    const currentUserResponse = await api.get(`/user/${login}`);
    const user = currentUserResponse.data.user;

    const accessToken = signJwtAccessToken(user);

    const result = {
      ...user,
      accessToken,
    };

    return result;
  } catch (error) {
    console.log(error)
  }
};

export default getUser;


// code triggered to send an event to webscoket
interface FriendProps {
  friendId: string;
}

const createMessage = async (
  friendId: FriendProps,
  content: FormDataEntryValue | null
) => {
  const user = await getUser();
  const friendsId = friendId;
  const userId = user.id;
  const receiver = await api.get(
    `receiverUserId/${userId}/friend/${friendsId}`
  );
  const receiverId = receiver.data.receiverId[0].id;

  try {
    socket.emit("send-msg", {
      content,
      friendsId,
      userId,
      receiverId,
    });
  } catch (error) {
    console.log(error);
  }
};

export default createMessage; ```

I need a fast way of building customizable websites with potentially complex features that WordPress doesn’t support

I need a fast way of building customizable websites with potentially complex features that WordPress doesn’t support. So far I used HTML/CSS/JS with help of Chat-GPT to reduce repeatable tasks, and this way of coding is too slow for me. WordPress and other clones of WordPress help speed things up, but aren’t suitable for complex features. Does anyone have suggestion for web development tools like WordPress, with ability to “drag and drop” components, but allows me to have full control over the code it generates, and allows me to add my own code?

Why is setinterval not working the way I am setting it to?

I’m trying to make a game where the user can fire a bullet, but the bullet function is not working.

When you press space, the first fire works perfectly. Then every time you press space after that, the bullet gets faster and faster. Why?

let container = document.getElementById('container')
let character = document.getElementById('character')
let characterCoordinates = {
  x: 600,
  y: 500
}
let newBulletCoordinates = {
  x: 0,
  y: 0
}
let speed = 30
let bulletSpeed = 50
let containerRect = container.getBoundingClientRect()
window.addEventListener('load', function() {
  character.style.top = characterCoordinates.y + 'px'
  character.style.left = characterCoordinates.x + 'px'
})

function shoot() {
  let newBullet = document.createElement('div')
  container.appendChild(newBullet)
  newBullet.classList.add('bullet')
  newBulletCoordinates.x = characterCoordinates.x + 15
  newBulletCoordinates.y = characterCoordinates.y - 50
  newBullet.style.left = (characterCoordinates.x + 15) + 'px'
  newBullet.style.top = (characterCoordinates.y - 50) + 'px'
  setInterval(function() {
    newBulletCoordinates.y -= bulletSpeed
    newBullet.style.top = newBulletCoordinates.y + 'px'
    let newBulletRect = newBullet.getBoundingClientRect()
    if (newBulletRect.top < containerRect.top) {
      newBullet.remove()
    }
  }, 100)
  setInterval(function() {
    newBullet.remove()
  }, 2000)
}
window.addEventListener('keydown', function(e) {
  let key = e.key
  let characterRect = character.getBoundingClientRect()
  if (key === 'ArrowLeft') {
    if (characterRect.left > containerRect.left) {
      characterCoordinates.x -= speed
    }
  } else if (key === 'ArrowRight') {
    if (characterRect.right < containerRect.right) {
      characterCoordinates.x += speed
    }
  } else if (e.code === 'Space') {
    shoot()
  }
  character.style.top = characterCoordinates.y + 'px'
  character.style.left = characterCoordinates.x + 'px'
})
<div id="container">
  <div id="character"></div>
  <div id="bullet"></div>
</div>

Vue async request with axios

Description:

I’m encountering an issue with a Vue.js component where playerEl.value becomes null after an asynchronous Axios request, causing the component to fail to render.

Problem:

I have a Vue.js component where I’m fetching some data asynchronously using Axios in the onMounted hook. After fetching the data, I’m trying to append a player element to a div with the ID player, which is referenced by a ref named playerEl. However, it seems that playerEl.value becomes null after the Axios request, leading to a failure in rendering the component.

<script setup>
import { onMounted, ref } from "vue";
import axios from "axios";
var gameData;
const slug = window.location.pathname.split('/').pop();

const playerEl = ref(null);

onMounted(async () => {
  try {
    const response = await axios.get(`https://api.flasoyun.com/game/${slug}`);
    gameData = response.data;
    console.debug(gameData)
    const ruffle = window.RufflePlayer.newest();
    const player = ruffle.createPlayer();
    playerEl.value.appendChild(player);
    //const slug = window.location.pathname.split('/').pop();
    player.load(`/games/${slug}.swf`);

  } catch (error) {
    console.error('Error fetching game data:', error);
  }
});
</script>

<template>
  <div>
    <div class="container">
      <div class="row g-4">
        <div class="col-lg-8 mx-auto">
          <h2>{{ gameData.title }}</h2>
          <div class="ratio ratio-16x9">
            <div id="player" ref="playerEl"></div>
          </div>

          <div>
            {{ gameData.content }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

HTML nested Div drag and resize on different div’s

I have been trying and browsing, but no luck.
Abstract:
I have a “parent” div wrapper as a Modal. This one I like to drag and resize. Needless to say, whatever is encapsulated should be dragged as well.
Now the “child” div, I like to resize and perhaps even drag independently. Once the “parent” one is large enough.
Additional caveat, the child contains select boxes which should also be resizable, no need to drag those, but if that comes for free, I take it.

Toss the syntax, the pseudo code would be something like this:

    <div "parent" resize and drag>
    <div "child" resize and drag within "parent">
    <div "data" resize and drag within "child">
    <select>
    </select>
    <select>
    </select>
    </div> /*data*/
    </div> /*child*/
    </div> /*parent*/

I get either the resize OR the drag to fly, but not both, let alone independently from child.

Any hints?

Some solution to the upper Problem.

How can I convert jQuery code to JavaScript code?

Help me, plz, need to remake this jQuery code to JS:

$(window).scroll(function(){ $('.container p').each(function(){ var scrollTop = $(window).scrollTop(), elementOffset = $(this).offset().top, distance = (elementOffset - scrollTop), windowHeight = $(window).height(), breakPoint = windowHeight*0.9; if(distance > breakPoint) { $(this).addClass("more-padding"); } if(distance < breakPoint) { $(this).removeClass("more-padding"); } }); });

No idea. Just need JS code.

Codepen: https://codepen.io/jm/pen/nOyqjZ

NextJS helper function is not a function

I tried making a function in NextJS but when I try to call it, I get an error saying that something is not a function.enter image description here

Here’s the code of the function that I am trying to invoke here

'use client'

export const t = (l:string) =>{
    if(typeof window !== 'undefined'){
        return window.location
    }
}

The problem goes away when I remove “use client” statement but then I cannot use window object that I desperately need now

Scroll the people list in Facebook list doesn’t work when mouse cursor is not on scrolling bar

I would like to scroll down, up to the maximum end of the scroll on https://www.facebook.com/friends/requests page, but I quite don’t understand how it works here.

When I scroll by myself my cursor have to be in the area of people friendship request so the scroll bar is visible here if I scrolled down myself and scroll bar is visible I can use

var element = document.querySelector('.x1p6kkr5'); element.scrollIntoView(); in browser console to make it scroll down, but if I didn’t scrolled down it myself completely it doesn’t work. Case it doesn’t work at all is when scroll bar is invisible here I receive this:

VM1363:1 Uncaught TypeError: Cannot read properties of null (reading 'scrollIntoView')
    at <anonymous>:1:60

I wonder how I can make it scroll down without me needing to hold mouse cursor on friends request tab and make it scroll without my assistance on first scroll?

In java spring boot application , html does not load a function from the js file

I have an html file in it a button that should call a function from the js file but it is not called.

HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Registration</title>
</head>
<body>
<script type="text/javascript" src="/js/auth.js" th:inline="javascript"></script>

<button onclick="btnOpenModal()">open modal</button>


<dialog class="modal" id="modal">
    <h2>Registration</h2>
    <p>FORM</p>
    <button>SUBMIT</button>
</dialog>
</body>
</html>

JS file:

function btnOpenModal() {
    console.log("HELLO")
}

Files structure: click

Exception: click

For which values does template string literal throws?

A simple template literal expression:

`${value}`

… will throw TypeError in at least two cases:

try {
  `${Symbol('nope')}`
} catch (error) {
  console.error(`${error.name}: ${error.message}`)
}
  • if value is an empty non-inherited object.
try {
  `${Object.create(null)}`
} catch (error) {
  console.error(`${error.name}: ${error.message}`) // weird error message in this case: "No default value"
}

What are the other cases in which it throws an error, if any? Is there some universal rule for that (like, not having some method used internally)?

Need help figuring out short regex – how to match 1 a char, then either of a set including the char, then another char

My regex does not match phrases as intended, and I don’t know if it’s possible or not to do what I’m trying to.

Intended match (as string progresses)

  • phrase starts with t
  • FIRST character after beginning ‘t’ must not be ‘t’
  • has any number of ‘t’ or ‘y’ characters (can be 0)
  • must end with y

Should match:

  • ty
  • tytyyy

Should not match:

  • tty
  • tyt

Regex

/t[ty]*y/

this will match ty
but it will also match tty

Other Regex

t(?!t)[ty]*y

this matches tty for some reason, even though I clearly specify there cannot be a t after the initial t, after which there can be any number of t and y, and it should end with y?

I am trying to find a middleground but no matter how I change my regex, it ends up failing at least 1 other check i mentioned in the list above.

create ‘uploads’ folder in root path of repo in production server

In my development server I have wrote a code to create a folder called ‘uploads’ where routes and controller folders exists. But when I pushed code to server, In production it is throwing error to create that folder. Below is this error,
Error creating uploads folder: [Error: EACCES: permission denied, mkdir ‘/home/ubuntu/anofy/dist/anomalify-server/uploads

const folderName = "uploads";
const folderPath = path.join(__dirname, folderName);


     fs.stat(folderPath, (err, stats) => {
    if (err) {
      // Folder doesn't exist, create it
      if (err.code === "ENOENT") {
        fs.mkdir(folderPath, (err) => {
          if (err) {
            console.error("Error creating uploads folder:", err);
          } else {
            console.log("Uploads folder created successfully.");
          }
        });
      } else {
        console.error("Error checking uploads folder:", err);
      }
    } else {
      // Folder exists
      console.log("Uploads folder already exists.");`your text`
    }
  });

Overflow makes item in absolute position disapearing

So I have a specific timeline with several month that can go beyond its container and no scroll is available. The month are inside a div but are visually positionned on top of it with relative/absolute combo.If I decide to do overflow: “auto” to see the last items of the timeline then the month disappears.

here is my code:

const Timeline = () => {

 const monthsBetween = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul'];

  return (
      <div style={{ width: `${monthsBetween.length * 150}px` }}>
        <div style={{ width: `${monthsBetween.length * 150}px`, border: '1px solid lightgrey', height: '50px', position: 'relative', display: 'flex', flexDirection: 'row' }}>
          {monthsBetween.map((month, index) => (
            <div key={index} >
              <p style={{ position: 'absolute', top: '-35px', left: `calc(150px * ${index + 1})`, transform: 'translateX(-50%)' }}>{month}</p>
              <div style={{
                position: 'absolute',
                top: '0',
                left: `calc(150px * ${index + 1})`,
                borderLeft: "1px solid lightgray",
                height: "50px",
              }} />
            </div>
          ))}
        </div>
      </div>
    )
}

I know that the problem is in the position with CSS,I can still see the bottom of the month appearing but I cannot not find a way to fix it, here it looks without overflow:

enter image description here

And here with the overflow:

enter image description here

And it still does not scroll on the right.