What is the syntax for JavaScript’s CSS supports method?

I am testing out the new :has() pseudo class. So far, only Firefox hasn’t enabled it by default.

I read in a comment on How do you enable :has() selector on Firefox about the following test:

CSS.supports("selector(:has(:focus))"));

It returns true when I’ve enabled the setting on Firefox, and false otherwise, which is expected.

The thing is what does the selector(:has(:focus)) actually mean? Obviously it’s testing for the :has() pseudoclass, but what’s with the selector() and the (:focus) parts. If I try to simplify it, the test doesn’t work — at least it returns a false.

I can’t find any detailed document on the CSS.supports() method which discusses it.

I’m not able access the close button through keyboard

I’m not able to access the close image button through keyboard even I’ve added tabindex=0 In img src

I’m not able to access the close image button through keyboard even I’ve added tabindex=0 in img src= “close img link” tabindex=”0″ alt= “close” title=”close” aria-labelledby=”close”

How to auction NFT on Stellar Blockchain using javascript?

I am new to Stellar Blockchain. As I understand the blockchain didn’t have any smart contracts involved originally and I have already minted a NFT using the Operations they provide. But what I don’t get now how to add metadata to this NFT? There is no Operation that does that. Again I am not clear how to put this NFT on auction or for sale in a decentralised manner.

I tried minting and I was successful in it. I minted an Asset and locked its issuer account so that its total supply remains One so in theory creating an NFT. But I used manageData Operation and added a field “ipfsLink” with the value a URL of an image uploaded on IPFS. But this image doesn’t show on the stellar.expert explorer.

How to show an multidimensional object using in HTML table page

I have the given below object and I wanted to get the output as attached png file in HTML as shown in the attachment. In the given object the “dayCalendarRows” can be N numbers of records and each record can be editable and that is also shown in an image. I can be either in standard HTML table or Material Table.

[
    {
        "DayId": 3,
        "DayName": "Wed",
        "MealGroupId": null,
        "dayCalendarRows": [
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": null,
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 0,
                "Day": 3,
                "DayName": "Wed",
                "DayHeader": "Wed",
                "WeekName": "Current week",
                "PreDeliveryWeekName": "Wed(Current week)",
                "IndexNumber": -1
            }
        ]
    },
    {
        "DayId": 2,
        "DayName": "Tue",
        "MealGroupId": null,
        "dayCalendarRows": [
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": null,
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 0,
                "Day": 2,
                "DayName": "Tue",
                "DayHeader": "Tue",
                "WeekName": "Current week",
                "PreDeliveryWeekName": "Tue(Current week)",
                "IndexNumber": -1
            },
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": "2ceff4ad-fcfd-4169-bb23-d6769b1167e6",
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 1,
                "Day": 2,
                "DayName": "Tue",
                "DayHeader": "Tue",
                "WeekName": "Previous week",
                "PreDeliveryWeekName": "Tue(Previous week)",
                "IndexNumber": 2
            }
        ]
    },
    {
        "DayId": 5,
        "DayName": "Fri",
        "MealGroupId": null,
        "dayCalendarRows": [
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": null,
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 0,
                "Day": 5,
                "DayName": "Fri",
                "DayHeader": "Fri",
                "WeekName": "Current week",
                "PreDeliveryWeekName": "Fri(Current week)",
                "IndexNumber": -1
            }
        ]
    },
    {
        "DayId": 4,
        "DayName": "Thu",
        "MealGroupId": null,
        "dayCalendarRows": [
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": null,
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 0,
                "Day": 4,
                "DayName": "Thu",
                "DayHeader": "Thu",
                "WeekName": "Current week",
                "PreDeliveryWeekName": "Thu(Current week)",
                "IndexNumber": -1
            },
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": "2ceff4ad-fcfd-4169-bb23-d6769b1167e6",
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 1,
                "Day": 4,
                "DayName": "Thu",
                "DayHeader": "Thu",
                "WeekName": "Previous week",
                "PreDeliveryWeekName": "Thu(Previous week)",
                "IndexNumber": 2
            }
        ]
    },
    {
        "DayId": 0,
        "DayName": "Sun",
        "MealGroupId": null,
        "dayCalendarRows": [
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": null,
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 0,
                "Day": 0,
                "DayName": "Sun",
                "DayHeader": "Sun",
                "WeekName": "Current week",
                "PreDeliveryWeekName": "Sun(Current week)",
                "IndexNumber": -1
            },
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": "ef35c158-41b4-4430-bbdd-15de415736d0",
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 0,
                "Day": 0,
                "DayName": "Sun",
                "DayHeader": "Sun",
                "WeekName": "Current week",
                "PreDeliveryWeekName": "Sun(Current week)",
                "IndexNumber": 1
            },
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": "1ef22a16-3613-493a-9fe8-ca98d7100357",
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 0,
                "Day": 0,
                "DayName": "Sun",
                "DayHeader": "Sun",
                "WeekName": "Current week",
                "PreDeliveryWeekName": "Sun(Current week)",
                "IndexNumber": 6
            }
        ]
    },
    {
        "DayId": 1,
        "DayName": "Mon",
        "MealGroupId": null,
        "dayCalendarRows": [
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": null,
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 0,
                "Day": 1,
                "DayName": "Mon",
                "DayHeader": "Mon",
                "WeekName": "Current week",
                "PreDeliveryWeekName": "Mon(Current week)",
                "IndexNumber": -1
            }
        ]
    },
    {
        "DayId": 6,
        "DayName": "Sat",
        "MealGroupId": null,
        "dayCalendarRows": [
            {
                "ICustomerId": "00000000-0000-0000-0000-000000000000",
                "ICustomerDGroupId": "00000000-0000-0000-0000-000000000000",
                "Inherited": false,
                "Id": "00000000-0000-0000-0000-000000000000",
                "BCDinerGroupId": "00000000-0000-0000-0000-000000000000",
                "MealCategoryId": null,
                "MealClosingTimeGroupId": null,
                "MealDeliveryTypeId": null,
                "MealGroupName": null,
                "DeliveryMomentName": null,
                "DeliveryMethodName": null,
                "OnHolidayText": null,
                "WeekDay": 0,
                "DaysBefore": 0,
                "OnHoliday": false,
                "Week": 0,
                "Day": 6,
                "DayName": "Sat",
                "DayHeader": "Sat",
                "WeekName": "Current week",
                "PreDeliveryWeekName": "Sat(Current week)",
                "IndexNumber": -1
            }
        ]
    }
]

This is what I have done till now but its showing correct for only one record if there are multiple records then its not giving me proper output:

<table class="mat-table">
            <thead>
                <tr class="mat-header-row">
                    <th class="mat-header-cell">&nbsp;</th>
                    <th class="mat-header-cell" *ngFor="let header of deliveryCalendarDataList">{{header.dayName}}</th>
                </tr>
            </thead>

            <tbody>
                <tr class="mat-row">
                    <td class="mat-cell">
                        <tr class="mat-row">{{'Meal Group'| translate}}</tr>
                        <tr class="mat-row">{{'Delivery Method'| translate}}</tr>
                        <tr class="mat-row">{{'Delivery Moment'| translate}}</tr>
                        <tr class="mat-row">{{'Delivery Days'| translate}}</tr>
                        <tr class="mat-row">{{'Pre Delivery Days'| translate}}</tr>
                        <tr class="mat-row">{{'Delivery on Public Holiday'| translate}}</tr>
                    </td>
                    <td class="mat-cell" *ngFor="let row of deliveryCalendarDataList; let k = index">
                        <!--{{i}}-->
                        <tr class="mat-row" *ngFor="let dayRecords of row.dayCalendarRows">
                            {{dayRecords.dayName}}
                        </tr>
                        <tr class="mat-row" *ngFor="let dayRecords of row.dayCalendarRows">
                            {{dayRecords.preDeliveryWeekName}}
                        </tr>
                        <tr class="mat-row" *ngFor="let dayRecords of row.dayCalendarRows">
                            {{dayRecords.weekName}}
                        </tr>
                        <tr class="mat-row">{{k}}</tr>
                        <tr class="mat-row">{{k}}</tr>
                        <tr class="mat-row">{{k}}</tr>
                    </td>

                 </tr>
            </tbody>
        </table>

This is how it should look

This is how it should look but in this any day can have more then one record of columns and first column of left side labels should also come in next rows as well

{“error”:”Error parsing request: missing request parameter”} In Nodejs

I’m currently facing an issue while trying to connect Node.js with KSQL. I have a KSQL table that I can query successfully using KSQL, but when I attempt to connect to it from Node.js using the ksqlExample.js file, I encounter an error.

Here’s a simplified version of my ksqlExample.js file:

const WebSocket = require('ws');
const serverUrl = 'ws://localhost:8088/ws/query';
const query = 'SELECT * FROM Test_transactionWithkeytableQueryable;';
const ws = new WebSocket(serverUrl);
ws.on('open', () => {
ws.send(query);
});
ws.on('message', (data) => {
console.log(data);
});
ws.on('error', (error) => {
console.error(error);
});
const query = 'SELECT * FROM Test_transactionWithkeytableQueryable;';
executeKsqlQuery(query);

When I executed the script node ksqlExample.js, the response I received was in the form of a buffer:

<Buffer 7b 22 65 72 72 6f 72 22 3a 22 45 72 72 6f 72 20 70 61 72 73 69 6e 67 20 72 65 71 75 65 73 74 3a 20 6d 69 73 73 69 6e 67 20 72 65 71 75 65 73 74 20 70 ... 10 more bytes>

To convert the buffer to a string, I used the data.toString() method. However, after applying this change, I encountered the following error message:

{"error":"Error parsing request: missing request parameter"}

The updated script with the toString() method is as follows:

const WebSocket = require('ws');
const serverUrl = 'ws://localhost:8088/ws/query';
const query = 'SELECT * FROM Test_transactionWithkeytableQueryable;';
const ws = new WebSocket(serverUrl);
ws.on('open', () => {
ws.send(query);
});
ws.on('message', (data) => {
console.log(data.toString());
});
ws.on('error', (error) => {
console.error(error);
});

I have verified that the table name (Test_transactionWithkeytableQueryable) and the KSQL server URL (http://localhost:8088) are correct. The table is queryable using KSQL, so it seems to be an issue specific to connecting from Node.js.

Can someone please help me understand what might be causing this error and how to resolve it? I would greatly appreciate any guidance or suggestions to overcome this issue.

Thank you in advance for your assistance.

React, socket.io page refresh continues without confirmation prompt selection

I am a beginner and I am trying to have a confirmation dialog box appear when a user refreshes a page so they can decide whether or not they want to leave the page. When a user clicks on the browser refresh, the confirmation box appears but the user disconnects automatically from socket server before making a selection.

import React, { useState, useEffect, useCallback, useMemo } from "react";
// ... (other imports and code)

function Game() {
  // ... (previous code)
 const location = useLocation();
  const [shouldPrompt, setShouldPrompt] = useState(true);
  const [initialRender, setInitialRender] = useState(true);

    useEffect(() => {
    const unloadCallback = (event) => {
      event.preventDefault();
      event.returnValue = "";
      return "";
    };

    window.addEventListener("beforeunload", unloadCallback);
    return () => window.removeEventListener("beforeunload", unloadCallback);
  }, []);

const handlePopstate = useCallback(
    (event) => {
      event.preventDefault();
      event.stopPropagation();

      if (shouldPrompt) {
        const shouldLeave = window.confirm(
          "Are you sure you want to leave the page?"
        );

        if (shouldLeave) {
          if (isHost && hasOpponent) {
            socket.emit("new_host", room);
          } else {
            socket.emit("leave_room", room);
          }
          navigate("/");
        } else {
          window.history.pushState(null, null, window.location.pathname);
        }
      }
    },
    [hasOpponent, isHost, navigate, room, shouldPrompt, socket]
  );

  useEffect(() => {
    window.addEventListener("popstate", handlePopstate);

    return () => {
      window.removeEventListener("popstate", handlePopstate);
    };
  }, [handlePopstate]);

  useEffect(() => {
    if (!initialRender) {
      setShouldPrompt(true);
    } else {
      setInitialRender(false);
    }
  }, [initialRender, location.pathname]);

  useEffect(() => {
    if (shouldPrompt) {
      const unblock = navigate((tx) => {
        if (tx.action === "POP" && location.pathname === "/game") {
          return false;
        }
      });

      return unblock;
    }
  }, [navigate, shouldPrompt, location.pathname]);

  useEffect(() => {
    if (!socket.connected) {
      navigate("/");
    }
  }, [socket, navigate]);


  // Rest of the component...
}

export default Game;

I’ve tried multiple variations of handling “beforeunload” and they all have the same result of the refresh action automatically happening despite no selection made on the confirmation prompt that appears.

When adding a react project to github, the page only displays the name of the app

I tried chat gpt and google guides , but it didn’t work

I have tried these steps
Install GitHub Pages package: Install the gh-pages package, which will help you deploy your app to GitHub Pages.
bash
Copy code
npm install gh-pages –save-dev
Configure deployment script: In the package.json file, add the following lines under the scripts section:
json
Copy code
“scripts”: {
“predeploy”: “npm run build”,
“deploy”: “gh-pages -d build”,

the code is on https://github.com/FriedSk8r/Keeper-App

I have a problem with my navbar. I am using React and I have an issue when changing state, my navbar is getting bigger. I am using TailwindCSS

I have a light and dark mode. When in light mode, the toggle button is below the navbar, as expected but when I switch to dark mode, my navbar gets bigger and now the toggle button is in it. I want the button to be below the navbar whether or not in light or dark mode, and I want the navbar to stay the same size.

My navbar component:

import React from "react";

export default function Navbar({ toggleTheme }) {
    return (
        <header className="bg-gray-800 md:sticky top-0 z-10 reset navbar" style={{ height: '60px' }}>
            <div className="container mx-auto p-5 text-center md:grid md:grid-cols-3 md:items-center">
                <div className="col-span-2 flex flex-col md:flex-row md:items-center md:text-left">
                    <a className="title-font font-medium text-white mb-4 md:mb-0" style={{ lineHeight: '1.5' }}>
                        <a href="#about" className="ml-3 text-xl" style={{ margin: 0, padding: 0 }}>
                            My Name
                        </a>
                    </a>
                    <nav className="md:ml-10 md:py-1 md:pl-4 md:border-l md:border-gray-700 flex flex-wrap items-center justify-center md:justify-start text-base">
                        <a href="#projects" className="mr-5 hover:text-white">
                            Past Work
                        </a>
                        <a href="#skills" className="mr-5 hover:text-white">
                            Skills
                        </a>
                        <a href="#contact" className="mr-5 hover:text-white">
                            Contact
                        </a>
                    </nav>
                </div>
            </div>
        </header>
    );
}

My ToggleButton component:

import React from "react";
import { ThemeContext } from '../ThemeContext';

export default function LightDarkModeToggle({ toggleTheme }) {
    const { themeMode } = React.useContext(ThemeContext);

    return (
        <div className="container mx-auto p-5 flex items-center justify-end">
            <div className="flex items-center ml-2">
                <span className={`text-sm font-medium ${themeMode === 'light' ? 'text-black' : 'text-white'}`}>
                    Light
                </span>
                <label className="relative inline-flex items-center cursor-pointer ml-2">
                    <input
                        type="checkbox"
                        value=""
                        className="sr-only peer"
                        onChange={toggleTheme}
                    />
                    <div
                        className={`w-9 h-5 ${themeMode === 'light' ? 'bg-yellow-600' : 'bg-green-500'} bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 ${themeMode === 'light' ? 'dark:peer-focus:ring-yellow-600' : 'dark:peer-focus:ring-green-500'} rounded-full peer dark:white peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-gray-600 ${themeMode === 'light' ? 'peer-checked:bg-yellow-600' : 'peer-checked:bg-green-500'}`}
                    />
                    <span className={`ml-2 text-sm font-medium ${themeMode === 'light' ? 'text-black' : 'text-white'}`}>
                        Dark
                    </span>
                </label>
            </div>
        </div>
    );
}

Before I had the toggle button in the Navbar component but decided to move it below it and had this issue since. I also tried to create a CSS file but it did not make any change:

.toggle-container {
  height: 60px;
}

Is there any way to emulate the behavior of a reference to a primative in JS?

I am writing a browser extension that runs on top of a javascript game for which the code is minified/obfuscated. Every time the game is updated, all the symbols change but the majority of the behavior remains the same. In an attempt to save myself work in the future, I started attempting to define references to the symbols used so an update would only require updating the references rather than changing every variable name throughout the code.

For objects, this method works perfectly.

tla.property = 4
usefullName = tla
tla.property = 5
console.log(usefullName.property) // => 5
usefullName.property = 6
console.log(tla.property) // => 6

However, I don’t believe it’s possible to create a reference to a primitive.

unk = 4
usefullVarName = unk
unk = 5
console.log(usefullVarName) // => 4 Desired 5

When researching my problem, the most common answer was to wrap the primitive in an object. This solution does not work for me since I don’t control how the original unk is used throughout the game.

A friend recommended using get, which I don’t fully understand, but the resulting code got me 1/2 way to my desired behavior.

unk = 4
usefullVarNameGetter = () => {
  return unk
}
Object.defineProperty(globalThis, 'usefullVarName', { get: usefullVarNameGetter});
unk = 5
console.log(usefullVarName) // => 5
usefullVarName = 6
console.log(unk) // => 5 Desired 6

I also started looking into proxys, however they don’t seem to apply to my use case since I intend to alter the value of the original variable by altering the value of the reference.

Is there any way to make this work? Is there a better approach that I haven’t thought of? Any help would be greatly appreciated.

useNavigate not redirecting ReactJs

I am trying to make a post request and when the data has been sent I want the function to redirect me to the ‘/games’ page where the games are being displayed from the SQL data base.

For some reason when I click on the button to execute the request the data is sent but is not redirecting. The data is added to the SQL data base.

I don’t know what am I missing.

Here is my code

import { useNavigate } from 'react-router-dom'
import './Create.css'
import { useState } from 'react';
import Axios from 'axios'

const Create = () => {
    
    // helps me to redirect to another page
    const navigate = useNavigate();
    
    //To get the input text information
    const [game, setGame] = useState('');
    const [genre, setGenre] = useState('');
    const [year, setYear] = useState(0);
    const [platform, setPlatform] = useState('');

    const [showError, setShowError] = useState(false);

    const addGame = () => {

        //to show error messagge when there is not text content in the inputs
        if (!game || !genre || !year || !platform) {
            setShowError(true)
            return; // prevent the post request to be made
        }

        Axios.post('http://localhost:3001/create',
            {
                game: game,
                genre: genre,
                year: year,
                platform: platform
            })
            .then((result) => {
                console.log('added succesfully')
                navigate("/games");
            }).catch((err) => {
                console.log('error mesagge' + err)
            });
    }

    return (
        <div className="create">
            <div className="create-container ">
                <h2 className="create-title headtext-h2">Add a Game</h2>
                <form className="create-form">
                    <label className='create-label headtext-label'>Game Name</label>
                    <input type="text" className='create-input ' onChange={(e) => {
                        setGame(e.target.value);
                    }} />
                    <label className='create-label headtext-label'>Genre</label>
                    <input type="text" className='create-input' onChange={(e) => {
                        setGenre(e.target.value);
                    }} />
                    <label className='create-label headtext-label'>Year</label>
                    <input type="number" className='create-input' onChange={(e) => {
                        setYear(e.target.value);
                    }} />
                    <label className='create-label headtext-label'>Platform</label>
                    <input type="text" className='create-input' onChange={(e) => {
                        setPlatform(e.target.value);
                    }} />
                    { showError && (
                        <div className="error">Please fill all the fields</div>
                    )}
                    <button type='button' className='create-button neon-button-form' onClick={()=>{addGame()}}>ADD</button>
                </form>
            </div>
        </div>
    );
}

export default Create;
```

This is my container that has the routers
```
import Home from './Home';
import Create from './Create';
import Games from './Games'


import {BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'
import './Container.css'


const Container = () => {
    return (
        <div className="container">
            <Router>
            <Link to={'/'} className='home-button neon-button-form'>Home</Link>
                <Routes>
                    <Route exact path="/" element={<Home></Home>}></Route>
                    <Route exact path="/create" element={<Create></Create>}></Route>
                    <Route exact path="/games" element={<Games></Games>}></Route>
                </Routes>
            </Router>
        </div>
    );
}

export default Container;
```

Thank you so much for your help!!

Merging two arrays together so that non existing values dropped from original

I would like to create an algorithm (or use an existing js library/fn) that would merge two arrays together so that

  • values are dropped from the results that are not in the replacing array compared to original
  • value is added if not exist in the original array
  • duplicates are not added
  • Arrays does not have to be same size

E.g.

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4]; // 2 is missing and 5,4 are new compared to the original

const result = merge(originalArray, replacingArray); 

console.log(result) // [1,5,3,4]

How could I achieve that? What would be the merge function?

Compare two array of object and find the matches

I have a set of variations of array of object it maybe change the variant name defends on the situation.

The variant looks like enter image description here

And have selected Color and Size

I already create a function that will manipulate the data and get the id
variantType = variantName and variantId is just my checker if may be case duplicate variant name but different Id, “White, Black, blue ….” are the variant options. And same with the pattern in the Color and Size.

selected = [
  {
    variantId: "6475c7b102ce2b9279eef5d0",
    optionId: "6475c7b102ce2b9279eef5d2",
    variantType: "Size",
  },
  {
    variantId: "6475c7e702ce2b9279eef5dc",
    optionId: "6475c7e702ce2b9279eef5de",
    variantType: "Color",
  },
]

And there’s an array of SKU’s

Example :

variantSkus = [
  {
      "_id": "64afc53d7b2df03cf6b99e49",
      "merchId": "64afc53d7b2df03cf6b99e44",
      "variant": [
          {
              "variantId": {
                  "_id": "6475c7e702ce2b9279eef5dc",
                  "variantName": "Color",
                  "options": [
                      {
                          "_id": "6475c7e702ce2b9279eef5de",
                          "variantId": "6475c7e702ce2b9279eef5dc",
                          "optionName": "White",
                          "isTrashed": false,
                          "dateCreated": "2023-05-30T09:54:47.277Z",
                          "lastUpdated": "2023-05-30T09:54:47.277Z"
                      },
                      {
                          "_id": "6475c7e702ce2b9279eef5df",
                          "variantId": "6475c7e702ce2b9279eef5dc",
                          "optionName": "Black",
                          "isTrashed": false,
                          "dateCreated": "2023-05-30T09:54:47.277Z",
                          "lastUpdated": "2023-05-30T09:54:47.277Z"
                      },
                      {
                          "_id": "6475c7e702ce2b9279eef5e0",
                          "variantId": "6475c7e702ce2b9279eef5dc",
                          "optionName": "Blue",
                          "isTrashed": false,
                          "dateCreated": "2023-05-30T09:54:47.277Z",
                          "lastUpdated": "2023-05-30T09:54:47.277Z"
                      },
                      {
                          "_id": "6475c7e702ce2b9279eef5e1",
                          "variantId": "6475c7e702ce2b9279eef5dc",
                          "optionName": "Red",
                          "isTrashed": false,
                          "dateCreated": "2023-05-30T09:54:47.277Z",
                          "lastUpdated": "2023-05-30T09:54:47.277Z"
                      },
                      {
                          "_id": "6475c7e702ce2b9279eef5e2",
                          "variantId": "6475c7e702ce2b9279eef5dc",
                          "optionName": "Yellow",
                          "isTrashed": false,
                          "dateCreated": "2023-05-30T09:54:47.277Z",
                          "lastUpdated": "2023-05-30T09:54:47.277Z"
                      }
                  ],
                  "isTrashed": false,
                  "dateCreated": "2023-05-30T09:54:47.273Z",
                  "lastUpdated": "2023-05-30T09:54:47.287Z"
              },
              "option": {
                  "_id": "6475c7e702ce2b9279eef5de",
                  "variantId": "6475c7e702ce2b9279eef5dc",
                  "optionName": "White",
                  "isTrashed": false,
                  "dateCreated": "2023-05-30T09:54:47.277Z",
                  "lastUpdated": "2023-05-30T09:54:47.277Z"
              },
              "_id": "64afc53d7b2df03cf6b99e4a"
          },
          {
              "variantId": {
                  "_id": "6475c7b102ce2b9279eef5d0",
                  "variantName": "Size",
                  "options": [
                      {
                          "_id": "6475c7b102ce2b9279eef5d2",
                          "variantId": "6475c7b102ce2b9279eef5d0",
                          "optionName": "Extra Small",
                          "isTrashed": false,
                          "dateCreated": "2023-05-30T09:53:53.699Z",
                          "lastUpdated": "2023-05-30T09:53:53.699Z"
                      },
                      {
                          "_id": "6475c7b102ce2b9279eef5d3",
                          "variantId": "6475c7b102ce2b9279eef5d0",
                          "optionName": "Small",
                          "isTrashed": false,
                          "dateCreated": "2023-05-30T09:53:53.699Z",
                          "lastUpdated": "2023-05-30T09:53:53.699Z"
                      },
                      {
                          "_id": "6475c7b102ce2b9279eef5d4",
                          "variantId": "6475c7b102ce2b9279eef5d0",
                          "optionName": "Medium",
                          "isTrashed": false,
                          "dateCreated": "2023-05-30T09:53:53.700Z",
                          "lastUpdated": "2023-05-30T09:53:53.700Z"
                      },
                      {
                          "_id": "6475c7b102ce2b9279eef5d5",
                          "variantId": "6475c7b102ce2b9279eef5d0",
                          "optionName": "Large",
                          "isTrashed": false,
                          "dateCreated": "2023-05-30T09:53:53.700Z",
                          "lastUpdated": "2023-05-30T09:53:53.700Z"
                      }
                  ],
                  "isTrashed": false,
                  "dateCreated": "2023-05-30T09:53:53.421Z",
                  "lastUpdated": "2023-05-30T09:53:53.767Z"
              },
              "option": {
                  "_id": "6475c7b102ce2b9279eef5d2",
                  "variantId": "6475c7b102ce2b9279eef5d0",
                  "optionName": "Extra Small",
                  "isTrashed": false,
                  "dateCreated": "2023-05-30T09:53:53.699Z",
                  "lastUpdated": "2023-05-30T09:53:53.699Z"
              },
              "_id": "64afc53d7b2df03cf6b99e4b"
          }
      ],
      "price": 100,
      "stock": 100,
      "isTrashed": false,
      "dateCreated": "2023-07-13T09:34:53.794Z",
      "lastUpdated": "2023-07-13T09:34:53.802Z",
      "sku": "SQDIU9E49",
      "selectedOption": [
          {
              "variantId": "6475c7e702ce2b9279eef5dc",
              "optionId": "6475c7e702ce2b9279eef5de",
              "variantType": "Color"
          },
          {
              "variantId": "6475c7b102ce2b9279eef5d0",
              "optionId": "6475c7b102ce2b9279eef5d2",
              "variantType": "Size"
          }
      ]
  }]

That will compare the selectedOption and selected and return the root object of the array and get the price SKU

The problem is that it returns all the sku’s which is only 1 or if there’s a same match in selected and selected option it return the price value

I already have the code snippet.

I hope someone help me with this problem.

Thanks

How to insert html element just before body closing tag as last loading

I got a page that loads several add-ons and I need to insert html element (script) just before body closing tag (</ body>) as last loading. I tried some javascript methods such as appendChild and insertAdjacentElement, but none of them did work because of other scripts that load as well.

What I have done so far and didn’t work:

Using appendChild or insertAdjacentElement got same result:

var myscript = document.createElement('script');
myscript.setAttribute('src','https://xxxxx/myscript.min.js');
myscript.async = true;
document.body.appendChild(myscript);  or  document.body.insertAdjacentElement('beforeend', myscript);

Result:

<body>
   <element1>
   <element2>
   *<myscript> <--- inserted here*
   <element3>
   <element4>
   <element5>
   <element6>
   <element7>
</body>

Expected result:

<body>
   <element1>
   <element2>
   <element3>
   <element4>
   <element5>
   <element6>
   <element7>
   *<myscript> <--- insert here*
</body>

How can I create timeline chart using Javascript with given array?

[I’m facing problem to create assign the timeline container in new grid column](https://i.stack.imgur.com/v6IAa.png)](https://i.stack.imgur.com/v6IAa.png)
This is my current code.
“`
function displayTimeline() {
//name, start time, end time, display duration, frequency type, start date, end date, select filter date
var timelineArray = [
[“Signage 2”, “16:00:00”, “19:00:00”, “30”, “2”, “2023-07-19”, “2023-07-21”, “2023-07-19”],
[“food”, “16:00:00”, “19:00:00”, “30”, “3”, “2023-07-19”, “2023-07-21”, “2023-07-19”],
[“food”, “16:00:00”, “19:00:00”, “30”, “3”, “2023-07-19”, “2023-07-21”, “2023-07-19”],
[“test f&b”, “16:00:00”, “02:00:00”, “30”, “3”, “2023-07-19”, “2023-08-06”, “2023-07-19”],
[“same duration”, “04:00:00”, “10:00:00”, “30”, “1”, “2023-07-19”, “2023-07-24”, “2023-07-19”],
[“frew”, “16:00:00”, “19:00:00”, “12”, “2”, “2023-07-19”, “2023-07-21”, “2023-07-19”]
];

    var pushStartTime = [];
    var pushEndTime = [];
    var pushStartDatetime = [];
    var pushEndDatetime = [];

    for (var i = 0; i < timelineArray.length; i++) {
        var getStart = timelineArray[i][1];
        var start = getStart.split(':');
        var start_seconds = (+start[0]) * 60 * 60 + (+start[1]) * 60 + (+start[2]);
        var start_exposure = start_seconds / 150;
        pushStartTime.push(start_exposure);

        var getEnd = timelineArray[i][2];
        var end = getEnd.split(':');
        var end_seconds = (+end[0]) * 60 * 60 + (+end[1]) * 60 + (+end[2]);
        var end_exposure = end_seconds / 150;
        pushEndTime.push(end_exposure);
    }

    for (var i = 0; i < timelineArray.length; i++) {
        var getStartTime = timelineArray[i][1];
        var getStartDate = timelineArray[i][5];
        var start_datetime = getStartDate + " "+ getStartTime;
        pushStartDatetime.push(start_datetime);

        var getEndTime = timelineArray[i][2];
        var getEndDate = timelineArray[i][6];
        var end_datetime = getStartDate + " "+ getEndTime;
        pushEndDatetime.push(end_datetime);
    }

    var showTable = [];

    for (var c = 0; c < timelineArray.length; c++) {
        showTable.push([
        timelineArray[c][0],
        pushStartTime[c],
        pushEndTime[c],
        timelineArray[c][3],
        timelineArray[c][4],
        timelineArray[c][5],
        timelineArray[c][6],
        timelineArray[c][7],
        pushStartDatetime[c],
        pushEndDatetime[c]
        ]);
    }


    var trackCounter = 1;
    var currentTrack = "track-" + trackCounter;

    for (var i = 0; i < showTable.length; i++) {
        var div = document.createElement("div");
        div.innerHTML = '<div class="session ' + currentTrack + '"><h3 class="session-title">' + showTable[i][0] + '</h3></div>';  //showTable[i][0] = campaign name

        // div.style.gridColumn = "track-" + trackCounter + " / track-" + (parseInt(showTable[i][3]) + trackCounter - 1);
        // trackCounter += parseInt(showTable[i][3]);

        // Check if the current item overlaps with any previous items
        var overlap = false;
        for (var j = 0; j < i; j++) {
            var startTime1 = showTable[i][8];
            var endTime1 = showTable[i][9];
            var startTime2 = showTable[j][8];
            var endTime2 = showTable[j][9];
            console.log(i + " i: " + startTime1 + " until " + endTime1);
            console.log(j + " j: " + startTime2 + " until " +endTime2);    

            if ((startTime1 >= startTime2 && startTime1 <= endTime2) || (endTime1 >= startTime2 && endTime1 <= endTime2) ||
                (startTime2 >= startTime1 && startTime2 <= endTime1) || (endTime2 >= startTime1 && endTime2 <= endTime1)) {
                    overlap = true;
                    break; 
                    //DateTime overlap, increase track 
                  //      trackCounter++;
                   // currentTrack = "track-" + trackCounter;
                   
            }
            // else{
            //     //put in new track 1
            //         trackCounter = 1;
            //         currentTrack = "track-" + trackCounter;
            // }
            if (overlap) {
                // Overlap found, start a new track
                trackCounter++;
                currentTrack = "track-" + trackCounter;
            }
        }

        div.style.gridColumn = "track-" + trackCounter + " / track-" + (parseInt(showTable[i][3]) + trackCounter-1);
        trackCounter += parseInt(showTable[i][3]);


        if (showTable[i][2] > showTable[i][1]) { //if end exp greater than start exp
            div.style.gridRow = "e-" + showTable[i][1] + "/ e-" + showTable[i][2];   //one container
        } else {
            if (showTable[i][5] == showTable[i][7]) { //first date = filter date
                div.style.gridRow = "e-" + showTable[i][1] + "/ e-" + 576; //first day : 10pm-12am
            } else if (showTable[i][6] == showTable[i][7]) { // last day = filter date 
                div.style.gridRow = "e-" + 1 + "/ e-" + showTable[i][2]; //last day : 12am-2am
            } else if (showTable[i][7] > showTable[i][5] && showTable[i][7] < showTable[i][6]) {
                div.style.gridRow = "e-" + 1 + "/ e-" + showTable[i][2];

                var div2 = document.createElement("div");
                div2.innerHTML = '<div class="session ' + currentTrack + '"><h3 class="session-title">' + showTable[i][0] + '</h3></div>';
                div2.style.gridColumn = currentTrack;
                div2.style.gridRow = "e-" + showTable[i][1] + "/ e-" + 576;

                document.getElementById("schedule_id").appendChild(div2);
            }
        }

        div.style.color = '#fff';

        if (showTable[i][4] == 1) {
            var frequency_type = ' (Full Exposure)';
            div.classList.add("full_exp");
        } else if (showTable[i][4] == 2) {
            var frequency_type = ' (Half Exposure)';
            div.classList.add("half_exp");
        } else if (showTable[i][4] == 3) {
            var frequency_type = ' (Quarter Exposure)';
            div.classList.add("quarter_exp");
        }

        div.innerHTML = showTable[i][0] + frequency_type;
        div.classList.add("session");

        document.getElementById("schedule_id").appendChild(div);
    }

    $(".full_exp").css("background-color", "#1259B2");
    $(".half_exp").css("background-color", "#687f00");
    $(".quarter_exp").css("background-color", "#bc8f8f");

    }

    displayTimeline();
Current result:

Signage 2 (Half Exposure)
food (Quarter Exposure)
food (Quarter Exposure)
test f&b (Quarter Exposure)
same duration (Full Exposure)
frew (Half Exposure)
“`
Expected result:
“`
Signage 2 (Half Exposure)
food (Quarter Exposure)
food (Quarter Exposure)
test f&b (Quarter Exposure)
same duration (Full Exposure)
frew (Half Exposure)
“`