Binary Search Tree remove node, sometimes it works, sometimes it doesnt

I’m currently working on the odin project on Binary Search Tree. I’m trying to make deleteNode work, and I’m working on removing a node if it is a leaf node.

Here’s my code:


class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

class BinarySearchTree {
  constructor() {
    this.root = null;
  }
  buildTree(array) {
    //accepts an array of integers and sort them into binary search tree;
    //loop through the given array, creating a node for each item. insert nodes into the array in a binarySearchTree  manner.
    array.forEach((item) => {
      this.insert(item);
    });
  }
  insert(value) {
    //accepts an integer value and sort it into the tree;
    let newNode = new Node(value);
    if (this.root === null) {
      this.root = newNode;
      return this;
    }
    let current = this.root;
    while (true) {
      if (value === current.value) return undefined;
      if (value < current.value) {
        if (current.left === null) {
          current.left = newNode;
          return this;
        }
        current = current.left;
      } else if (value > current.value) {
        if (current.right === null) {
          current.right = newNode;
          return this;
        }
        current = current.right;
      }
    }
  }

 deleteNode(value) {
    let current = this.root;
    let prev;
    if (!current) {
      console.log("hello");
      return undefined;
    }
    while (current) {
      if (current.value > value) {
        prev = current;
        current = current.left;
      } else if (current.value < value) {
        prev = current;
        current = current.right;
      } else {
        //node found.
        //case 1: node is leaf node, no left and right children
        if (!current.left && !current.right) {
          if (prev.value > current.value) {
            prev.left = null;
          } else {
            prev.right = null;
          }

          console.log("leaf node deleted", current);
          return this;
        }
        //case 2: node has either left or right child
        //case 3: node has both left and right children
      }
    }
  }
  find(value) {
    //accepts an integer value and search for it in the tree. IF found ,return the node with the value;
    if (this.root === null) {
      return undefined;
    }
    let current = this.root;
    while (current) {
      if (current.value === value) {
        return current;
      } else if (current.value > value) {
        current = current.left;
      } else {
        current = current.right;
      }
    }
    return false;
  }

  levelOrder(callback) {
    //BFS
    const queue = [];
    const data = [];
    let node = this.root;
    queue.push(this.root);
    while (queue.length) {
      node = queue.shift();
      data.push(node.value);
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
    return data;
  }

  inOrder(callback) {
    //inOrderDFS
    if (this.root === null) {
      return undefined;
    }
    const data = [];
    let current = this.root;
    const traverse = (node) => {
      if (node.left) {
        traverse(node.left);
      }
      data.push(node.value);
      if (node.right) {
        traverse(node.right);
      }
    };
    traverse(current);
    return data;
  }
  preOrder(callback) {
    //preOrderDFS
    if (this.root === null) {
      return undefined;
    }
    const data = [];
    let current = this.root;
    const traverse = (node) => {
      data.push(node.value);
      if (node.left) traverse(node.left);
      if (node.right) traverse(node.right);
    };
    traverse(current);
    return data;
  }

  postOrder(callback) {
    //postOrderDFS
    if (this.root === null) {
      return undefined;
    }
    const data = [];
    let current = this.root;
    const traverse = (node) => {
      if (node.left) traverse(node.left);
      if (node.right) traverse(node.right);
      data.push(node.value);
    };
    traverse(current);
    return data;
  }
}

const odinTree = new BinarySearchTree();
const array = [10, 20, 12, 15, 11, 50, 35, 21, 5, 2, 9, 3];
odinTree.buildTree(array);

Here’s the code for deleteNode:

 deleteNode(value) {
    let current = this.root;
    let prev;
    if (!current) {
      console.log("hello");
      return undefined;
    }
    while (current) {
      if (current.value > value) {
        prev = current;
        current = current.left;
      } else if (current.value < value) {
        prev = current;
        current = current.right;
      } else {
        //node found.
        //case 1: node is leaf node, no left and right children
        if (!current.left && !current.right) {
          if (prev.value > current.value) {
            prev.left = null;
          } else {
            prev.right = null;
          }

          console.log("leaf node deleted", current);
          return this;
        }
        //case 2: node has either left or right child
        //case 3: node has both left and right children
      }
    }
  }

I tried running the code on console, and it actually worked. However, I tried refreshing the page and I pressed keyup to run the same code to delete the same leaf node and it got stuck.

I’m quite sure my code is fine because i tried typing out tree.deleteNode on several leaf nodes and they all worked. The page only got stuck whenever i tried running deleteNode by pressing keyup.

Any inputs would be appreciated, thank you!

socket.io not firing on production mode when live reload page. but firing on dev mode

import { socket } from "../../socket";
  useEffect(() => {
   socket.emit("sedo-domain-list");

    socket.on("sedo-domain-list", (domain) => {
      setData(domain);
      console.log(domain);
      socket.off("sedo-domain-list");
    });

    return () => {
      socket.off("sedo-domain-list");
    };
  }, []);

This is my code. This code working fine in dev mode but when I build the nextjs project, its not firing on first page reload or live reload. but firing on when I change the routes and returned to the page.

And this is my socket.js file

import io from "socket.io-client";
export const socket = io("http://localhost:5000");

And this is my server file

socket.on("sedo-domain-list", () => {
    console.log("logging", socket.id)
}

Please help

Issue with Displaying Data in ShadCN Data Table Using JavaScript in Next.js

I’m working on a Next.js project where I’m trying to implement a data table using ShadCN’s Data Table component. The examples provided are in TypeScript, but since I’m not familiar with TypeScript, I tried to convert the logic into JavaScript. However, I’m running into some issues.

Initially, I encountered the error: TypeError: Cannot destructure property 'columns' of 'data' as it is undefined. To resolve this, I added a ternary operator to handle undefined data, which removed the error, but now I’m facing a new issue: the table displays a message saying No data available, even though I’ve defined the data.

Here are the relevant code snippets:

./data/data.js

export const data = {
  columns: [
    {
      Header: "ID",
      accessor: "id",
    },
    // other headers and accessors
  ],
  data: [
    {
      fullName: "Morlee Tapson",
      email: "[email protected]",
      salary: 30000.0,
      currency: "INR",
    },
    // other data here
  ],
};

/components/ReusableTable.jsx

import {
  Table,
  TableCaption,
  TableHeader,
  TableCell,
} from "@/components/ui/table";
import {
  flexRender,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table";
import Link from "next/link";

export default function ReusableTable({
  data,
  captionLink = "",
  captionText = "",
}) {
  const { columns, rows } = data || {}; //data mentioned

  console.log("columns:", columns); // returns undefined
  console.log("rows:", rows); // returns undefined

  const table = useReactTable({
    columns: columns || [], // Fallback to empty array if undefined
    data: rows || [], // Fallback to empty array if undefined
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <>
      <Table className="mt-5">
        <TableCaption className="text-left">
          <Link href={captionLink}>{captionText}</Link>
        </TableCaption>
        <TableHeader>
          {table.getHeaderGroups().map((headerGroup) => (
            <tr key={headerGroup.id}>
              {headerGroup.headers.map((header) => (
                <TableCell key={header.id}>
                  {flexRender(
                    header.column.columnDef.header,
                    header.getContext()
                  )}
                </TableCell>
              ))}
            </tr>
          ))}
        </TableHeader>
        <tbody>
          {table.getRowModel().rows.map((row) => (
            <tr key={row.id}>
              {row.getVisibleCells().map((cell) => (
                <TableCell key={cell.id}>
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </TableCell>
              ))}
            </tr>
          ))}
        </tbody>
      </Table>
    </>
  );
}

./app/page.jsx

import ReusableTable from "@/components/ReusableTable";
import { columns, data as rewardsData } from "@/data/data";
// other imports here

export default function Dashboard() {
  return (
    <>
      <div>
    {/* terneary operator*/}
        {rewardsData ? (
          <ReusableTable
            data={rewardsData}
            captionLink="/rewards-center"
            captionText="View More"
          />
        ) : (
          <p>No data available</p>
        )} 
      </div>
    </>
  );
}

Problem:

  • The console logs for columns and rows return undefined.
  • The table displays “No data available” even though data is defined in
    data.js.

What could be causing this issue, and how can I correctly pass the data to the table so that it displays as expected?

is there any embed/integrated ides you can put on a website (like leetcode and kattis)

is there any way to have a integrated area for writing code on a website? i want something like kattis and leetcode where you can write code that then gets complied, ran, and tested. currently the best i could come up with myself was a simple solution where i just have a textarea and eval(textarea.value) but this only supports js (to my knowledge). it would also have to be able to access and use js functions that ive made so embeds like jdoodle dont really work for me.

show value of product selected when button clicked?

How to show product added or removed when add or remove button is clicked?

Right now i have to pass the id of caption to get the text content. But this way i have to create same function for all products.

how to make it dynamic for every product?

document.querySelectorAll(".addProduct").forEach((btn) => {
  btn.addEventListener("click", ({target}) => {
    const proName = document.getElementById("flower-caption").textContent;

    document.getElementById("message").textContent = `${proName} Added.`;
  });
});
document.querySelectorAll(".removeProduct").forEach((btn) => {
  btn.addEventListener("click", ({target}) => {
    const proName = document.getElementById("flower-caption").textContent;

    document.getElementById("message").textContent = `${proName} Removed.`;
  });
});
<div class="product">
  <figure id="caption">
    <img src="images/flower.png" alt="Flowers" />
    <figcaption id="flower-caption">Beautiful Flower</figcaption>
  </figure>
  <button type="button" class="addProduct">Add To Cart</button>
  <button type="button" class="removeProduct">Remove From Cart</button>
</div>

<div class="product">
  <figure id="caption">
    <img src="images/parrot.png" alt="Parrot" />
    <figcaption id="parrot-caption">parrot</figcaption>
  </figure>
  <button type="button" class="addProduct">Add To Cart</button>
  <button type="button" class="removeProduct">Remove From Cart</button>
</div>

Webpack not recognizing css-loader despite it being in config

for some reason webpack is not recognizing css-loader, despite it being in the config and being installed. Here is my webpack.config.json

const path = require('path')

module.exports = {
  entry: './index.ts',
  module: {
    rules: [
      {
        test: /.ts?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /.css$/,
        use: ["css-loader", "style-loader"],
        exclude: /node_modules/
      },
      {
        test: /.scss$/,
        use: ["style-loader", "sass-loader"],
        exclude: /node_modules/
      }
    ],
  },
  resolve: {
    extensions: ['.ts', '.js', '.css'],
  },
  mode: "production",
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
}

here is my index.ts import:

import 'bulma/css/bulma'

finally, here is my package.json:

{
  "name": "wasm-emulator",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "dependencies": {
    "bulma": "^1.0.2",
    "jszip": "^3.10.1",
    "ts-loader": "^9.5.1",
    "typescript": "^5.5.4"
  },
  "devDependencies": {
    "webpack": "^5.94.0",
    "webpack-cli": "^5.1.4",
    "css-loader": "^7.1.2",
    "sass": "^1.77.8",
    "sass-loader": "^16.0.1",
    "style-loader": "^4.0.0"
  },
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

I keep getting this error which says no loader is defined despite it being clearly defined:

Module parse failed: Unexpected character ‘@’ (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are
configured to process this file. See https://webpack.js.org/concepts#loaders

I’m not sure what’s going on, everything looks right to me, is there something not glaringly obvious that I’m doing wrong?

How to rewrite or set sensitive header with got dependency

i’m working with internal library that wrapping got dependencies. and when i try to insert or request some data to 3rd api with this headers:

'Content-Type': 'application/json'
'X-Reference-Id': payload.accountNo
'X-Api-Key': 'example'
'X-Id': 'example'

got plugin convert the headers to lowercase like this:

'x-reference-id': payload.accountNo
'x-api-key': 'example'
'x-id': 'example'

and this is caused error to my request because headers for 3rd api is case sensitive.

can i rewrite or keep the headers in default form to avoid this? i can’t move to another dependency like axios or native method fetch (using those dependency solving my problem). but it’s not allowed because we are using internal and embedded library for our service.
please give me advice, thank you.

How to emite on-change event for the e8-form-table-column with a lookup in the column template?

Grid column with lookup.
On-change event for lookup doesn’t emit on-change event for the <e8-form-table>.

How to emit on-change event for the <e8-form-table> with a value row.uom from <e8-form-lookup>?

<e8-form-table-column
    internal-id="uom"
    width="100px"
    min-width="100px"
    max-width="100px"
    label-horizontal-alignment="center">
    <template #default="{ row, index }">
        <e8-form-lookup
            v-model="row.uom"
            :lazy-sync="false"
            :label="false"
            source="lstUnitsOfMeasure"
            placeholder="UOM">
        </e8-form-lookup>
    </template>
</e8-form-table-column>

Changing a spline in threejs dynamically

I have this code drawing a sinewave which works great, but when I call the function to draw it over again with different values, it doesn’t do anything. The code in the function is the exact same as prior to the function, but the sinewave code is /20 instead of /10 to give a different result. I then call sineUpdate() function separately, but there’s something I’m missing as to why it won’t update. I’ve used BufferGeometry before with straight lines and I can get things to update really well, but not sure how to do it with splines. Plus I would love to do everything in the fxn and not repeat code, but I don’t want to call scene.add(splineObject) everytime…only once.

var pointsSine = [];
for (var i=0, l=1000; i<=l; i++) {
    pointsSine.push(new THREE.Vector2(i, 25*Math.sin(i/10)));
}
var curve = new THREE.SplineCurve(pointsSine);
var points = curve.getPoints( 1000 );
var geometryspline = new THREE.BufferGeometry();
geometryspline.setAttribute("position", new THREE.BufferAttribute(new Float32Array(2*1000), 2));
geometryspline.setFromPoints(points3);
var materialspline = new THREE.LineBasicMaterial( { color: 0xff0000 } );
var splineObject = new THREE.Line( geometryspline, materialspline );
scene.add(splineObject);
splineObject.geometry.setDrawRange( 0, 1000 );
splineObject.geometry.attributes.position.needsUpdate = true;

function sineUpdate() {
    pointsSine = [];
    for (var i=0, l=1000; i<=l; i++) {
        pointsSine.push(new THREE.Vector2(i, 25*Math.sin(i/20)));
    }
    curve = new THREE.SplineCurve(pointsSine);
    points = curve.getPoints( 1000 );
    geometryspline = new THREE.BufferGeometry();
    geometryspline.setAttribute("position", new THREE.BufferAttribute(new Float32Array(2*1000), 2));
    geometryspline.setFromPoints(points);
    materialspline = new THREE.LineBasicMaterial( { color: 0xff0000 } );
    splineObject = new THREE.Line( geometryspline, materialspline );
    splineObject.geometry.setDrawRange( 0, 1000 );
    splineObject.geometry.attributes.position.needsUpdate = true;
}

Im trying to write unittest for a route handler using sinon and mocha and can’t stub using mocha

my route handler is, I wanna write using mocha and sinon and possibly supertest but if your code works in jest please send that too

router.post('/sign-up', async (req, res) => {
  try {
    const { username, password } = req.body
    await registerUser(username, password)

    res.status(201).send('user createdn')
  } catch (error) {
    if (error.message === 'username and password are required') {
      return res.status(400).send(error.message + 'n')
    }
    if (error.message === 'username already exists') {
      return res.status(409).send(error.message + 'n')
    }
    console.error(error)
    res.status(500).send('internal server errorn')
  }
})

I wanna stub await registerUser call to resolve it for testing, but It keeps calling the actual code hence causes connecting to database and hangs. the registerUser code is also

const bcrypt = require('bcrypt');
const saltRounds = 10;

// Import the repository functions
const userRepository = require('./userRepository');

async function registerUser(username, password) {
  if (!username || !password) {
    throw new Error('Username and password are required');
  }

  // Check if the username already exists in the database
  const existingUser = await userRepository.findOne({ username });
  if (existingUser) {
    throw new Error('Username already exists');
  }

  // Hash the password for storing in the database
  const hashedPassword = await bcrypt.hash(password, saltRounds);

  // Create and save the user to the database
  await userRepository.save({
    username,
    password: hashedPassword,
  });
}

module.exports = { registerUser };

I expect the registerUser to be resolved with stubbing Ideally using sinon.

Apple Pay/Google Pay payment sheets don’t dismiss and timeout after successful transaction through Stripe (web)

I’m encountering a strange problem where my payment sheets for Apple Pay and Google Pay are not receiving the result of a transaction through Stripe. I have alerts to log what is happening in my code, and the transactions are successful immediately as expected, but the payment sheets don’t react to this and end up timing out. Here is the JS for the payment button: (assume my code has my actual publishable stripe key)

function initializePaymentButton(businessId, basePrice) {
            const stripe = Stripe('pk_test_XXXXXXXXXXXXXXXXXXXXXXXX');
            const elements = stripe.elements();

            const paymentRequest = stripe.paymentRequest({
                country: 'US',
                currency: 'usd',
                total: {
                    label: 'Total',
                    amount: Math.round(basePrice * 100), 
                },
                requestPayerName: true,
                requestPayerEmail: true,
            });

            paymentRequest.canMakePayment().then(function(result) {
                if (result) {
                    const paymentButton = elements.create('paymentRequestButton', {
                        paymentRequest: paymentRequest,
                    });
                    paymentButton.mount(`#pay-button-container-${businessId}`);

                    paymentRequest.on('paymentmethod', async (ev) => {
                        const createPaymentIntent = httpsCallable(functions, 'createPaymentIntent');
                        const response = await createPaymentIntent({ businessId });

                        if (response.data.clientSecret) {
                            const { error, paymentIntent } = await stripe.confirmCardPayment(response.data.clientSecret, {
                                payment_method: ev.paymentMethod.id,
                            });

                            if (error) {
                                alert(`Payment failed: ${error.message}`);
                            } else {
                                alert(`Payment successful: PaymentIntent ID: ${paymentIntent.id}`);
                            }
                        } else {
                            alert("Failed to create PaymentIntent.");
                        }
                    });
                } else {
                    alert('Google/Apple Pay is not available');
                }
            }).catch((error) => {
                alert('Error checking payment availability: ' + error.message);
            });
        }

Here is an image of the result on iPhone: ‘Payment Not Completed’ after timeout, with succesful purchase alert behind it

I added supportedNetworks:

supportedNetworks: ['visa', 'mastercard', 'amex', 'discover'],
And that didn’t make a difference. I checked the logs for my paymentIntent function on my server and the transaction activity on Stripe, and nothing seems out of the ordinary. I’m guessing I’m missing something fundamental on the client-side, but I just can’t find it. I tested this on android and I get the same result, though it takes Google Pay a lot longer to time out. In both cases, the transactions happen as they should in the background, and technically everything works except for the payment sheets receiving the result.

Why does Angular 18 SSR seem like CSR in local tests?

I’m currently running an angular 18 SSR app in mi local machine; my app consumes a graphql api using apollo.

I haven’t errors with the functionality but when i check in the browser, in the inspections tool in network (fetch), i see the api graphql consume and i understand when an app is SSR, that type of consume must not appear in network browser, the another problem is when in the browser i disable javascript, the app SSR functionality doesn’t works; then my app angular SSR is working bad or i’m not having another concept in mind?.

Maybe because in my app i configure the access to the localstorage of the user with this?

BrowserStorageService.ts:

import { Inject, Injectable, InjectionToken } from '@angular/core';

export const BROWSER_STORAGE = new InjectionToken<Storage>('Browser Storage', {
  providedIn: 'root',
  factory: () => localStorage,
});

@Injectable()
  export class BrowserStorageService {
  constructor(@Inject(BROWSER_STORAGE) public storage: Storage) {}

get(key: string) {
  return this.storage.getItem(key);
}

set(key: string, value: string) {
 this.storage.setItem(key, value);
}

remove(key: string) {
  this.storage.removeItem(key);
}

clear() {
 this.storage.clear();
}
}

app.config.server.ts:

import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
import { BrowserStorageService } from '@core/services/browser-storage.service';
import { BrowserStorageServerService } from '@core/services/browser-storage-server.service';

const serverConfig: ApplicationConfig = {
  providers: [
   provideServerRendering(),
   {
    provide: BrowserStorageService,
    useClass: BrowserStorageServerService,
   }
  ]
};

export const config = mergeApplicationConfig(appConfig, serverConfig);

Deleting saved jobs in LinkedIn

I new to programming and still learning. I am trying to mass unsave jobs I have applied to via LinkedIn because for some reason the jobs that I apply for, don’t go to applied jobs and remain in my saved jobs list. I have been trying to select the 3 dot drop down button and then click unsave but have been unsuccessful, wondering if anyone has an idea of where I am going wrong?

while not get_em:
# Obtain links to all saved jobs
job_elements = WebDriverWait(browser, 20).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ‘.reusable-search__result-container a.app-aware-link’)))
links = [job_element.get_attribute(“href”) for job_element in job_elements]

for jobs in job_elements:
    print("clicking 3 dot button")
    button = browser.find_element(By.CLASS_NAME, 'artdeco-dropdown__trigger ')
    button.click()
    time.sleep(5)
    print("clicking unsave button")
    xbutton = browser.find_element(By.CLASS_NAME, 'unsave-option-class')
    xbutton.click()

# Go to the next page or end
try:
    next_button = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.artdeco-pagination__button--next')))
    if next_button.is_displayed() and next_button.is_enabled():
        browser.execute_script("arguments[0].scrollIntoView();", next_button)   
        next_button.click()
        time.sleep(5)
        counter += 1
        print(f"Page number: {counter}")
        time.sleep(5)
   
except Exception as e:
    print(f"Next page button not found, at the end of all pages! or error occured:{e}")
    get_em = True

Trouble Replacing Scroll Event with IntersectionObserver

I’m working on a project where I want to highlight menu options when their corresponding sections reach the top of the viewport, with a 52px buffer. I initially implemented this using a scroll event listener, and it works well. Here’s the working code:

document.addEventListener('DOMContentLoaded', function () {
    const topMargin = 52;
    const activeClasses = ['font-bold', 'text-black'];

    const categories = document.querySelectorAll('.category');
    const menus = document.querySelectorAll('.menus');

    menus.forEach(menu => {
        const menuNav = menu.querySelector('.menu-nav');
        const links = menuNav.querySelectorAll('.category-link');

        window.addEventListener('scroll', function () {
            let currentCategory;

            categories.forEach((category, index) => {
                const rect = category.getBoundingClientRect();
                if (rect.top <= topMargin && rect.bottom > topMargin) {
                    currentCategory = category;
                }
            });

            if (currentCategory) {
                links.forEach(link => {
                    link.classList.remove(...activeClasses);
                    if (link.getAttribute('data-category') === currentCategory.id) {
                        link.classList.add(...activeClasses);

                        const navRect = menuNav.getBoundingClientRect();
                        const linkRect = link.getBoundingClientRect();

                        const scrollLeft = linkRect.left + menuNav.scrollLeft - navRect.left - (navRect.width / 2) + (linkRect.width / 2);

                        menuNav.scrollTo({
                            left: scrollLeft,
                            behavior: 'smooth'
                        });
                    }
                });
            }
        });
    });
});

Since this solution works fine, I wanted to optimize it by replacing the scroll event listener with an IntersectionObserver. However, when I tried this approach, it didn’t work as expected. Here’s my attempt with the IntersectionObserver:

document.addEventListener('DOMContentLoaded', function () {
    // Configuration variables
    const topMargin = 52; // The top margin (in pixels) to trigger the active link
    const activeClasses = ['font-bold', 'text-black']; // Classes to add to the active link

    const categories = document.querySelectorAll('.category');
    const menus = document.querySelectorAll('.menus');

    menus.forEach(menu => {
        const menuNav = menu.querySelector('.menu-nav');
        const links = menuNav.querySelectorAll('.category-link');

        // Create an Intersection Observer
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                const link = Array.from(links).find(link => link.getAttribute('data-category') === entry.target.id);

                if (entry.isIntersecting && link) { // Ensure link is found
                    links.forEach(link => link.classList.remove(...activeClasses));
                    link.classList.add(...activeClasses);

                    // Smooth scroll for the active link in the menu-nav
                    const navRect = menuNav.getBoundingClientRect();
                    const linkRect = link.getBoundingClientRect();
                    
                    const scrollLeft = linkRect.left + menuNav.scrollLeft - navRect.left - (navRect.width / 2) + (linkRect.width / 2);
                    
                    menuNav.scrollTo({
                        left: scrollLeft,
                        behavior: 'smooth'
                    });
                }
            });
        }, {
            rootMargin: `-${topMargin}px 0px 0px 0px`, // Trigger when the category is within the topMargin
            threshold: 0 // Trigger as soon as the element enters the viewport
        });

        // Observe each category
        categories.forEach(category => observer.observe(category));
    });
});

When I switch to the IntersectionObserver implementation, the menu highlighting and smooth scrolling do not work as desired. The menu items do not highlight correctly and seems to count from the bottom.

How can I correctly replace the scroll event with an IntersectionObserver to achieve the same effect?

document.addEventListener('DOMContentLoaded', function () {
            const topMargin = 52;
            const activeClasses = ['font-bold', 'text-black'];

            const categories = document.querySelectorAll('.category');
            const menus = document.querySelectorAll('.menus');

            menus.forEach(menu => {
                const menuNav = menu.querySelector('.menu-nav');
                const links = menuNav.querySelectorAll('.category-link');

                window.addEventListener('scroll', function () {
                    let currentCategory;

                    categories.forEach((category, index) => {
                        const rect = category.getBoundingClientRect();
                        if (rect.top <= topMargin && rect.bottom > topMargin) {
                            currentCategory = category;
                        }
                    });

                    if (currentCategory) {
                        links.forEach(link => {
                            link.classList.remove(...activeClasses);
                            if (link.getAttribute('data-category') === currentCategory.id) {
                                link.classList.add(...activeClasses);

                                const navRect = menuNav.getBoundingClientRect();
                                const linkRect = link.getBoundingClientRect();

                                const scrollLeft = linkRect.left + menuNav.scrollLeft - navRect.left - (navRect.width / 2) + (linkRect.width / 2);

                                menuNav.scrollTo({
                                    left: scrollLeft,
                                    behavior: 'smooth'
                                });
                            }
                        });
                    }
                });
            });
        });
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet"/>
<h1 class="text-3xl font-extrabold">Desiered Effect</h1>
    <!-- Example Menu 1: Breakfast Menu -->
    <div class="menus flex flex-col border border-gray-200 rounded-lg w-full p-3 mb-6">

        <!-- Menu title and description -->
        <div class="flex flex-col mb-4">
            <div class="font-bold text-xl">Breakfast Menu</div> <!-- Menu Name -->
            <div class="text-gray-600">Start your day right with our delicious breakfast options.</div> <!-- Menu Description -->

            <!-- Availability -->
            <div class="text-sm font-medium mt-2">
                <span>Monday - Friday: 6:00 AM - 11:00 AM</span>
            </div>
            <div class="text-sm font-medium">
                <span>Saturday - Sunday: 7:00 AM - 12:00 PM</span>
            </div>
        </div>

        <!-- Menu categories navigation -->
        <div class="menu-nav flex flex-row gap-x-4 overflow-x-scroll text-gray-600 whitespace-nowrap text-sm font-medium py-4 sticky top-0 bg-white">
            <a class="category-link cursor-pointer" href="#pancakes" data-category="pancakes">Pancakes</a>
            <a class="category-link cursor-pointer" href="#omelettes" data-category="omelettes">Omelettes</a>
            <a class="category-link cursor-pointer" href="#smoothies" data-category="smoothies">Smoothies</a>
        </div>

        <!-- Categories and items -->
        <div class="flex flex-col gap-y-3">
            <!-- Category 1: Pancakes -->
            <div id="pancakes" class="category flex flex-col gap-y-3 border border-red-200 p-3">
                <div class="text-2xl font-bold">Pancakes</div> <!-- Category Title -->

                <div class="flex flex-col md:flex-row gap-y-3 gap-x-3 md:basis-1/2 flex-nowrap">
                    <!-- Menu item 1 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Classic Pancakes</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">Fluffy pancakes served with maple syrup and butter.</div> <!-- Item Description -->
                        </div>
                    </div>
                    <!-- Menu item 2 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Blueberry Pancakes</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">Pancakes filled with fresh blueberries and served with a blueberry compote.</div> <!-- Item Description -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- Category 2: Omelettes -->
            <div id="omelettes" class="category flex flex-col gap-y-3 border border-red-200 p-3">
                <div class="text-2xl font-bold">Omelettes</div> <!-- Category Title -->

                <div class="flex flex-col md:flex-row gap-y-3 gap-x-3 md:basis-1/2 flex-nowrap">
                    <!-- Menu item 1 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Cheese Omelette</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">A fluffy omelette filled with cheddar, mozzarella, and parmesan cheese.</div> <!-- Item Description -->
                        </div>
                    </div>
                    <!-- Menu item 2 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Veggie Omelette</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">Omelette packed with spinach, mushrooms, bell peppers, and onions.</div> <!-- Item Description -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- Category 3: Smoothies -->
            <div id="smoothies" class="category flex flex-col gap-y-3 border border-red-200 p-3">
                <div class="text-2xl font-bold">Smoothies</div> <!-- Category Title -->

                <div class="flex flex-col md:flex-row gap-y-3 gap-x-3 md:basis-1/2 flex-nowrap">
                    <!-- Menu item 1 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Berry Blast Smoothie</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">A refreshing blend of strawberries, blueberries, and raspberries.</div> <!-- Item Description -->
                        </div>
                    </div>
                    <!-- Menu item 2 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Mango Tango Smoothie</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">Tropical smoothie with mango, pineapple, and a hint of lime.</div> <!-- Item Description -->
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <!-- Example Menu 2: Lunch Menu -->
    <div class="menus flex flex-col border border-gray-200 rounded-lg w-full p-3 mb-6">

        <!-- Menu title and description -->
        <div class="flex flex-col mb-4">
            <div class="font-bold text-xl">Lunch Menu</div> <!-- Menu Name -->
            <div class="text-gray-600">Our lunch menu features a variety of hearty meals and light bites.</div> <!-- Menu Description -->

            <!-- Availability -->
            <div class="text-sm font-medium mt-2">
                <span>Monday - Friday: 11:30 AM - 2:30 PM</span>
            </div>
        </div>

        <!-- Menu categories navigation -->
        <div class="menu-nav flex flex-row gap-x-4 overflow-x-scroll text-gray-600 whitespace-nowrap text-sm font-medium py-4 sticky top-0 bg-white">
            <a class="category-link cursor-pointer" href="#sandwiches" data-category="sandwiches">Sandwiches</a>
            <a class="category-link cursor-pointer" href="#salads" data-category="salads">Salads</a>
            <a class="category-link cursor-pointer" href="#soups" data-category="soups">Soups</a>
        </div>

        <!-- Categories and items -->
        <div class="flex flex-col gap-y-3">
            <!-- Category 1: Sandwiches -->
            <div id="sandwiches" class="category flex flex-col gap-y-3 border border-red-200 p-3">
                <div class="text-2xl font-bold">Sandwiches</div> <!-- Category Title -->

                <div class="flex flex-col md:flex-row gap-y-3 gap-x-3 md:basis-1/2 flex-nowrap">
                    <!-- Menu item 1 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Turkey Club</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">Sliced turkey, bacon, lettuce, tomato, and mayo on toasted bread.</div> <!-- Item Description -->
                        </div>
                    </div>
                    <!-- Menu item 2 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Grilled Cheese</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">A classic grilled cheese with cheddar on sourdough bread.</div> <!-- Item Description -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- Category 2: Salads -->
            <div id="salads" class="category flex flex-col gap-y-3 border border-red-200 p-3">
                <div class="text-2xl font-bold">Salads</div> <!-- Category Title -->

                <div class="flex flex-col md:flex-row gap-y-3 gap-x-3 md:basis-1/2 flex-nowrap">
                    <!-- Menu item 1 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Caesar Salad</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">Crisp romaine lettuce, croutons, parmesan, and Caesar dressing.</div> <!-- Item Description -->
                        </div>
                    </div>
                    <!-- Menu item 2 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Greek Salad</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">Mixed greens, cucumbers, tomatoes, olives, feta, and Greek dressing.</div> <!-- Item Description -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- Category 3: Soups -->
            <div id="soups" class="category flex flex-col gap-y-3 border border-red-200 p-3">
                <div class="text-2xl font-bold">Soups</div> <!-- Category Title -->

                <div class="flex flex-col md:flex-row gap-y-3 gap-x-3 md:basis-1/2 flex-nowrap">
                    <!-- Menu item 1 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Tomato Soup</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">Rich and creamy tomato soup served with a slice of garlic bread.</div> <!-- Item Description -->
                        </div>
                    </div>
                    <!-- Menu item 2 -->
                    <div class="flex flex-row border-b last:border-0 md:last:border md:border md:rounded-lg border-gray-200 pb-3 w-full md:p-3">
                        <div class="flex flex-col gap-y-1">
                            <div class="text-lg font-bold">Chicken Noodle Soup</div> <!-- Item Name -->
                            <div class="text-sm text-gray-600 pr-6">Hearty chicken soup with egg noodles, carrots, and celery.</div> <!-- Item Description -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Can’t Enter Text in to text box in html

I have input fields I created with HTML and when I run the page I cannot enter data in to the text boxes. I tried disabled=false but it did not work. The input fields I’m having problems with are email and password. I also placed the input fields in to a form. I also placed the input text boxes inside a div. Will this affect the program? Please help. Thanks.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #menu,
        #footer-menu {

            
            text-align: center;
            
        }

        

        nav {

            margin: auto;

            line-height: 60px;
        }

        header {
            margin: -8px;
            position: sticky;
            top: 0;
            height: 75px;
            background-color: antiquewhite;
        }

        

        a {
            margin: auto;
            text-decoration: none;
            font-size: 24px;
            color: black;
        }


        footer {
            position: absolute;
            bottom: 0;
            height: 75px;
            width: 100%;
            background-color: antiquewhite;
        }

        div#center {
            text-align: center;
           
        }


        input {
            margin: .1rem;
           
        }

        #label {
            position: relative;
            top: 73px;
            left: 35%;
                   }

        div#label {
            margin-top: .7rem;
            font-weight: bold;
            padding-top: .9rem;
            font-size: 18px;
        }

        h2 {
            text-align: center;
        }

     

        #register {
            display: inline;
            color: blue;
            text-decoration: underline;
        }

        #logbtn {
            position: absolute;
            width: 75px;
            height: 25px;
            background-color: green;
            display: inline;
            border-radius: 5px;
            left: 51%;
            color: white;
        }

        input[type=submit] {
            position: absolute;
            width: 75px;
            height: 25px;
            background-color: green;
            display: inline;
            border-radius: 5px;
            left: 51%;
            color: white;
        }

        #account {
            text-align: center;
            color: blue;
            text-decoration: underline;
        }

        #logo {
            float: left;
        }
    </style>

</head>

<body>
    <header><img src="logo.jpg" style="height: 75px; width: 75px;" id="logo">

        <div id="menu">
            <nav>
                <a href="index.html">Home|</a>
                <a href="math-facts.html">Games|</a>
                <a href="about.html">About|</a>
                <a href="login.html">Login</a>


            </nav>
        </div>

    </header>
    <form id="forma">
        <h2 id="h2">Log in</h2>
        <div id="label">
            <div>Email:</div>
            <div>Password:</div>

            <p id="register">Need an account? Register</p>

        </div>
        <!-- <form id="forma"> -->
        <div id="center">

            <!-- <label for="email">Email:</label> -->
            <input name="email" type="email" id="email"><br>

            <!-- <label for="password">Password:</label> -->
            <input type="password" id="password"><br><br>

            <input type="submit" value="Log in" id="sublogin"><br>
        </div>
    </form>

    <form id="formb">
        <h2 id="h2">Register</h2>
        <div id="label">
            <div>Email:</div>
            <div>Password:</div>
            <div>Repeat Password:</div>



        </div>



        <div id="center">

            <!-- <label for="email">Email:</label> -->
            <input name="email" type="email" id="email"><br>

            <!-- <label for="password">Password:</label> -->
            <input type="password" id="password"><br>

            <!-- <label for="password2">Repeat Password:</label> -->
            <input type="password" id="password2" name="password2"><br>



            <input type="checkbox" id="over"><label for="over">I am over 13 and like playing games.</label><br><br>

            <input type="submit" value="Register" id="subregister"><br>
        </div>
        <p id="account">Have an account? Log in</p>
    </form>





    <footer>
        <hr>
        <div id="footer-menu">
            <nav>
                <a href="contact-us.html"><img src="icon-contact-us.png"></a>
                <a href="https://instagram.com"><img src="icon-instagram.png"></a>
                <a href="https://twitter.com"><img src="icon-twitter.png"></a>
                <a href="https://facebook.com"><img src="icon-facebook.png"></a>


            </nav>
        </div>
    </footer>

    <script>

        window.addEventListener("load", function () { document.getElementById("formb").style.display = "none" });
        const register = document.getElementById("register");
        const login = document.getElementById("forma")
        register.addEventListener("click", function () {
            document.getElementById("forma").style.display = "none";
            document.getElementById("formb").style.display = "block";

        });


        const account = document.getElementById("account");
        account.addEventListener("click", function () {
            document.getElementById("formb").style.display = "none";
            document.getElementById("forma").style.display = "block";
        });

        const sublogin = document.getElementById("sublogin");
        sublogin.addEventListener("click", function () {
            alert("Form submitted")
        })

        const subregister = document.getElementById("subregister");
        subregister.addEventListener("click", function () {
            alert("Form submitted")
        })

        document.getElementById("forma").setAttribute("disabled", false);
          
    </script>




</body>

</html>