detect when horizontally animating element reaches center of viewport

Given an animating (transforming) row of images, detect when each one reaches the center so we can make some changes (e.g., adding styling like filter: grayscale)

row of images with one that is not black and white (as it reached middle of screen)

I’ve enlisted IntersectionObserver and gotten close. In fact my solution works great in Firefox but only works in Chrome if the mouse is moving and doesn’t work at all in Safari. Even if I tweak the options parameter behavior seems sporadic unless in Firefox.

Codepen

const options = {
  root: document.body,
  rootMargin: '0% -50% 0% -50%',
  threshold: 0,
}

const observer = new IntersectionObserver((entries) => { 
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.style.filter = 'grayscale(0%)'
    } else {
      entry.target.style.filter = 'grayscale(100%)'
    }
  })
}, options)

const items = document.querySelectorAll('.img-container img');
items.forEach(img => observer.observe(img))

How to dynamically increase the number of cells in GrapesJS Plugin Toolbox after updating the grid?

I’m using the GrapesJS Plugin Toolbox to build custom grids in my project. I can successfully define a grid layout and update it. However, after updating the grid, I’m struggling to find a way to dynamically increase the number of cells in the toolbox.

I have a grid set up with, say, 3×3 cells. After updating the grid to a new structure (e.g., 4×4), I want to add more cells to the toolbox and allow users to manipulate these new cells. However, I’m not sure how to handle the dynamic increase in the number of cells within the toolbox after the grid has been updated.

Has anyone faced this issue or knows how to programmatically increase the number of cells in the GrapesJS toolbox after the grid has already been updated?

How can i draw a list of svg files into a grid and have that grid repeat infinitely on both axis, then scroll based on mouse position…?

I am trying to create a wallpaper on “wallpaper engine” with the same effect as “https://dbrand.com/shop/limited-edition/icons” webpage. The way they have their java is confusing and following the code is daunting.

I literally went to the source of the code in the inspect element and downloaded everything. Then checked the code and deleted any fluff like the header and footer, and anything that was not the cool effect. i ended up with just my title and the two theme buttons on the bottom with out the icon scrolling background. I even took the svg file and separated them into 100 individual files to make a grid in html but realized if i want to have the infinite scroll effect i will need to draw them on a canvas and use java to do the math on where my cursor is to determine direction and speed. I’m not very literate in coding so if someone has a way to replicate the effect from “https://dbrand.com/shop/limited-edition/icons” then I’d greatly appreciate the help.

Button onclick shows hidden message javascript

The button needs to be edited in css to appear the way I have, that part worked. Then it needs to show a message that says “welcome to the world of coding!” upon clicking the button. I feel like it’s something very little but I’ve reread through this like 20x

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Greeting Page</title>
        <style>
        h1 {
            font-size: 14pt;
            text-align: center;
            }
        body {
            background-color: #eec0c8;
            font-family: Georgia;
            }
    button {
      background-color: rgb(245, 66, 132);
      padding: 33px;
      }
    button:hover {
        background-color: #ffffff;
              }
        </style>
    </head>
    <body>
        <h1> Welcome to my page! </h1>
        <p>This is a simple webpage created as a learning exercise.</p>
        <p> 
        <button onclick="hideUnhide(paragraph1)">Click to see a message!</button>
        </p>
        <p id="paragraph1">Welcome to the world of coding!</p>
      <script>
        function hideUnhide(id){
            const p1 = document.getElementById(id);
            if (p1.style.display == "none"){
                p1.style.display = "block";
            }
            else {
                p1.style.display = "none";
            }
        }
      </script>
    </body>
</html>

I am new to programming and I’m in a class. I have tried doing it 5 different ways and every time it will not allow the click function to show the message. I tried it in notepad++ and also in vs code. What am I doing wrong here? This is my last attempt I should’ve saved every version so I could ask about each one, but this one I followed the button directions verbatim from a YouTube video of someone doing the same thing in vs code and it did not work but they have it on video working.

I have an authContext file and an api route file. After login the navbar is returning null from the authContext. Why?

This is my authContext.js file which runs on load of the website.

"use client";

import { createContext, useContext, useState, useEffect } from "react";
import { auth } from "../firebase";
import { onAuthStateChanged } from "firebase/auth";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    console.log("AuthProvider is rendering");

    const unsubscribe = onAuthStateChanged(auth, (user) => {
      console.log("Auth state changed in provider:", user);
      setCurrentUser(user);
      setLoading(false);
    });

    return () => unsubscribe();
  }, []);

  return (
    <AuthContext.Provider value={{ currentUser, loading }}>
      {children}
    </AuthContext.Provider>
  );
};

export function useAuth() {
  return useContext(AuthContext);
}

When I try to login the navbar returns null for the current user. Here is the useEffect I have implemented in the navbar.

  const { currentUser } = useAuth();
  const [role, setRole] = useState(null);
  useEffect(() => {
    console.log('Current user in Navbar:', currentUser);
    if (currentUser) {
      const fetchUserRole = async () => {
        const userDoc = await getDoc(doc(firestore, "users", user.uid));

        if (userDoc.exists()) {
          const userData = userDoc.data();
          setRole(userData.role);
        } else {
          console.log("User document does not exist in Firestore.");
        }
      };

      fetchUserRole();
    } else {
      setRole(null);
    }
  }, [currentUser]);

I also have an api folder for the route.js file that does the backend firebase calls to create new users and to get the current user. This is all inside a export async function POST(request)

    // Sign In logic
    const userCredential = await signInWithEmailAndPassword(
      auth,
      email,
      password
    );
    const user = userCredential.user;

    // Retrieve role from Firestore by querying both collections
    let userRole = "unknown";
    const userDoc = await getDoc(doc(firestore, "users", user.uid));

    if (userDoc.exists()) {
      userRole = userDoc.data().role;
    } else {
      const vendorDoc = await getDoc(doc(firestore, "vendors", user.uid));
      if (vendorDoc.exists()) {
        userRole = vendorDoc.data().role;
      }
    }

    // Check if the user is an admin (You can have a flag like `isAdmin`)
    const adminDoc = await getDoc(doc(firestore, "admins", user.uid));
    if (adminDoc.exists()) {
      userRole = "admin"; // If user is admin, override role
    }

    console.log("User Role:", userRole);

    return new Response(
      JSON.stringify({
        message: `${userRole} signed in successfully`,
        role: userRole,
      }),
      { status: 200 }
    );

I am expecting the user to stay logged in so that the navbar can render some user information when logged in but the user keeps returning null after logging in. I checked the paths and when the user logs in it returns the new Response saying the specific role signed in successfully but the console.log in the navbar says the user is null.

Loop table dynamic header by month in Vue3.js

I want to show table date by month. How can I loop table data? Please show me.
enter image description here

I tried:

tableData: [
        {
          totalSale: 1,
          totalBorrow: 0,
          total: 1,
          details: [
            {
              date: moment("2024-08-01").format("DD/MM/YYYY"),
              totalSale: 1,
              totalBorrow: 0,
              total: 1,
            },
          ],
        },
        {
          totalSale: 2,
          totalBorrow: 1,
          total: 3,
          details: [
            {
              date: moment("2024-09-01").format("DD/MM/YYYY"),
              totalSale: 1,
              totalBorrow: 0,
              total: 1,
            },
          ],
        },
      ],

My result:

enter image description here

Back button not working as expected after increasing window.history.length on form submission

I am working on a Rails application and have a form that, upon submission, it to increase the window.history.length. I want the “Back” button to take the user back through all the history entries when clicked.

Here’s the structure of my code:

app/views/media/_form.html.slim

 $( ".form" ).submit(function(event) {
  $('.form').addClass('loading');
});

In the dashboard layout, I have a back button to allow users to navigate back through the history. Here’s the JavaScript for that:

_app/views/share/v2/menu.html.slim

document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('.back-button').addEventListener('click', (event) => {
    event.preventDefault();
    window.history.back();
  });
});

Problem:
Each time the user edits the form, window.history.length increases by the number of times they submit the form (e.g., 2 or 3 times). As a result, the user has to click the back button 2 or 3 times to go back to the previous page.

Expected Behavior:
When the user clicks the “Back” button, I want them to be taken directly to the previous page with one click, regardless of how many times the form was edited or submitted.

I have tried this

  document.addEventListener('DOMContentLoaded', () => {
    document.querySelector('.back-button').addEventListener('click', (event) => {
      event.preventDefault();
      var goback = window.history.length;
      window.history.go(-goback);
    });

back button not working, also tried

$( ".form" ).submit(function(event) {
  $('.form').addClass('loading');
  
  setTimeout(function() {
    window.history.go(0);
  }, 2000);
});

I have multiple forms in my Rails application (media, product, giveaway, league, etc.). I’m trying to use window.history.go(0) to reload the page after form submission without adding a timeout, but it only works when I add a setTimeout.

Problem: I don’t want to use a timeout for multiple forms. Without the timeout, window.history.go(0) doesn’t trigger. Is there a way to make it work without a delay? or any other solution to play around.

Thank you!!

@panzoom/panzoom does not work when cursor over element

const pz = document.getElementById('panzoom');
    console.log(pz)
    const panzoom = Panzoom(pz, {canvas: true, maxScale:5})
    pz.parentElement.addEventListener('wheel', panzoom.zoomWithWheel)
<script src="https://unpkg.com/@panzoom/[email protected]/dist/panzoom.min.js"></script>
<div style="width:1000px; height:600px; border: 1px solid black;">
    <iframe id="panzoom"  style="width:500px; height:300px; border: 10px solid black;" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiCNMl4OJrlzNToGd32IJd4RShAtxIMJb2hg&s"></iframe>
</div>

I am using this @panzoom/panzoom package to pan-zoom an iframe element. My code is like the following. However, I find that pan and zoom only works when mouse cursor is outside of the iframe. How can I make the pan and zoom still work even when the cursor is over the iframe element?

Deep Copy with circular reference in javascript

I’m making a game with a shop, and i want to make a copy of the list to keep the costs saved. i tried a standard listBak = list, but that just makes a reference to it, and a solution that should work is listBak = JSON.parse(JSON.stringify(list)), however. list contains an object that contains itself causing an infinite loop and erroring out. here is an example of how the original list is being made

import { Item } from "item.js"

export class Obg{
  
  list = []
  constructor(main /* includes this class */){
    this.list[0] = new Item("title", function buyFunc(){/* code executed when bought */}, main)
  }
}

the reason i need the shop item to have access to main is the fact that buyFunc() normally edits things that are outside of both the shop item, and the parent class. it can edit anything from any file, and i need that versatility, i would prefer to not list out the specific areas it can access. i am also using vanilla javascript, I’m using GitHub pages so i can’t use anything that requires a server


i have tried;

listBak = list : creates a link to list

listBak = JSON.parse(JSON.stringify(list)) : errors out due to circular reference

listBak = JSON.stringify(JSON.decycle(list)) : does not preserve functions in the object; using cycle.js from here

Following Row Selection Example breaks checkboxes in Material React Table(v3)

Followed the example but once I update the line onRowSelectionChange: setRowSelection, the checkboxes do not get checked once I click on them.
Not sure if it’s a re-render issue with the rowSelection not being passed back to the table properly.

This is pretty much exactly from the example but the checkboxes do not get checked when I click on them. But if I remove onRowSelectionChange: setRowSelection then the issue goes away.

type TableProps<T extends MRT_RowData> = {
  tablePropsObj: MRT_TableOptions<T>;
};

const Table = <T extends MRT_RowData>(props: TableProps<T>) => {
  const [pagination, setPagination] = useState({
    pageIndex: 0,
    pageSize: 10,
  });

  const [rowSelection, setRowSelection] = useState<MRT_RowSelectionState>({});
  
  const updatedTablePropsObj: MRT_TableOptions<T> = {
    enableColumnActions: false,
    enableRowSelection: true,
    enableSelectAll: true,
    enableTopToolbar: true,
    enableToolbarInternalActions: true,
    enableBottomToolbar: true,
    enablePagination: true,
    manualPagination: true,
    manualFiltering: true,
    positionPagination: 'bottom',
    onPaginationChange: setPagination,
    onRowSelectionChange: setRowSelection,
    state: {
      pagination,
      rowSelection,
    },
  }
  const table = useMaterialReactTable(updatedTablePropsObj);
  return (
    <>
      <MaterialReactTable table={table} />
    </>
  );
};

What are advanced concepts in frontEnd development

i have been studying JavaScript for a year now I just got started react and got to find out about nextjs and typescript. what other things should I learn pls so i am not left behind or stuck with learning something that is outdated or has advanced methods, and again pls any ideas on how i can host my project on vercel

i have been reading alot and not putting in the work and i guess thats why am still stuck with the level i am at programming i just need guide and tips from you all on how to get better

jam.py how to find the last item of a field and compute a running sum?

I am new with JAM.py and I am trying to create a maintenance database for aircraft.

On the form used to enter the data, I am entering the tachymeter time in (tach_in, beginning of the flight), and out (tach_out, end of the flight).

The computation of the flight duration is easy. Some pictures of the current state:

frontend form

variable names

I am struggling with the following:

a) Each time I am creating a new entry using the form, how can I automatically populate the new tach_in as equal to the previous (or last) tack_out? For example:

Flight N-2 tach_in = 100 tach_out = 101
FLight N-1 tach_in = 101 tach_out = 102

Flight N is the flight I am currently entering using the form: I would like to have the new tach_in = 102 (ie: the value of the previous/last tach_out, and I only have to enter the NEW tach_out)

Any idea on how to do that?

b) How can I perform a running sum of the flight time, to show the new total time (flight_total) after each entry?

Flight N-2 tach_in = 100 tach_out = 101 flight_duration = 1 flight_total = 1
FLight N-1 tach_in = 101 tach_out = 102 flight_duration = 1 flight_total = 2
Flight N   tach_in = 102 tach_out = 103 flight_duration = 1 flight_total = 3

Thank you for your help!

Google Map API Autocomplete pass an address manually without autoselecting

I have 2 search boxes with autocomplete.

The first search box is for user to select an address from google autocomplete.

I want to pass the address from the first search box to the second search box by default. The user can update the second search box if they choose to.

I tried passing the address to the second search box but got an error Unhandled rejection TypeError: Cannot read properties of undefined (reading ‘activeElement’)

Is there a way to do this?

//pass the full address from the first search box to the second search box
this.autocomplete(this.fulladdress);

//autocomplete function. This is also where I get the full address from the first search box
private autocomplete(input: any) {
    let autocomplete: google.maps.places.Autocomplete;

    autocomplete = new google.maps.places.Autocomplete(
      input
    );

    autocomplete.setComponentRestrictions({ country: ["au"] });

    autocomplete.addListener("place_changed", () => {
      let place = autocomplete.getPlace();

      if (place == null || place.address_components == null) {
        return;
      }
    ....
    this.fulladdress = place.formatted_address;
    ....
}

How does one access a closure property in the watch window in the browser debugging tools?

If I’m sitting at a breakpoint in the Chrome debugger in some JavaScript code, I can see the value of one of the function parameters in the “Scope” section inside a Closure:

enter image description here

Is there anything I can type into the Watch section to see that same value? I tried the parameter name (didn’t work), I tried e (didn’t work), I tried Yn.e and it also didn’t work.

Thanks!

Sequelize methods like create() are not working – how can I fix it?

I’m working on a project with Sequelize, but I encountered an issue where methods like create(), findOne(), and update() are not working as expected. The operations either don’t execute, return unexpected results, or throw errors.

Sequelize setup: I initialized Sequelize with a MySQL database connection, and models are properly defined. However, CRUD operations are failing.

Has Sequelize not been installed correctly? I generally don’t get errors from the console, but I encountered a property error: Cannot read properties of undefined (reading ‘findAll’). How can I fix this?

Has Sequelize not been installed correctly? I generally don’t get errors from the console, but I encountered a property error: Cannot read properties of undefined (reading ‘findAll’). How can I fix this?