How to make a non button element clickable using JavaScript

I am trying to make the cells on a 5×5 grid change to a random color when clicked on. I am having problems getting them to change when clicked. I am unsure of how to make a non button clickable and unsure about how to target multiple id’s in one statement vs doing it 25 times. I tried with jsut the first square to test it out and could link it correctly. I tried to get element by the first id and add event listener with click and change color function. I am almost positive that is my problem. When I do this my entire grid disappears.

html
<!doctype html>
<html lang="en-US">

<head>
<meta charset="UTF-8">

<title>YOUR title here</title>

<meta name="description" content="brief description of YOUR page here">
<meta name="keywords" content="keywords related to YOUR page here">
<meta name="author" content= "YOUR name here">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="grid.js" defer></script>
<link rel="stylesheet" href="grid.css"/>
</head>

<body>
    <div class="grid_container"></div>
    <div>
        <button id="reset">Reset Grid</button>
      </div>
</body>
</html>

………………………………………………………………………………………….
JavaScript
//linking elements to the script

document.getElementById('reset').addEventListener('click', reset);
document.getElementById('sqr0').addEventListener('click', change_color);


//function to create the grid cells

function create_grid(rows, cols){
    const grid_container = document.getElementsByClassName('grid_container')[0];

    for (let i = 0; i < rows; i++){
        for(let j = 0; j < cols; j++){
            const square = document.createElement('div');
            square.classList.add('square');
            grid_container.appendChild(square);
        }
    }
}

create_grid(5,5);


//function to assign unique id's to each square

function id(){
//targeting the grid div element, then the squares
const grid_div = document.querySelector('.grid_container');
const grid_cell = grid_div.querySelectorAll('.square'); 
//loop to create a unique id on each square
for (let i = 0; i < grid_cell.length; i++)
    grid_cell[i].id = "sqr" + i;
}

id();


//function to reset 

//just refreshing the entire page
function reset() {
    location.reload();
}


//function to generate a random color
//used https://css-tricks.com/ to help with generating random color

function get_random_color(){

    let random_color = math.floor(math.random()*16777215).tostring(16);
    return;
}


//function to change the background to a random color
function change_color(){
    element.style.backgroundColor = get_random_color();
}

......................................................................................................
css

/*making the grid container*/
.grid_container {
    display: grid;
    grid-template-columns: repeat(5, 50px);
    grid-template-rows: repeat(5, 50px);
    gap: 1px;
    }

    .square {
    aspect-ratio: 1;
    border: 1px solid black;
    background-color: white;
    }

TS/JS | How to use uppy for Images and video uploads to cloudflare

Am trying to impliment images, and video uploads to Cloudflare stream services and image services using Uppy/Tus, I have been wondering around the documentation of Uppy cannot figure the part where, Using Multiple Uploader Plugins in single instance of Uppy.

CF -> cloudflare.

Am using CF stream’s + CF images as for my media contents, and using Uppy dashboard.

and I want to use Tus in specific conditions, and also use Xhr on specific conditions only.

So, like using two Plugins in same instance is not going well as expected.
Because when a upload is triggered both the endpoints will be triggered.

//core-tsx
 const [ref] = useState(
    new Uppy({
      id: "xx-global-uploader---",
      debug: false,
    })
      .use(XHRUpload, {
        endpoint: endpoints.uploader("/uploads/v1/sign/image"),
        formData: true,
        fieldName: "file",
      })
      .use(Tus, {
        endpoint: "/uploads/v1/sign/video",
        addRequestId: true,
      })
  );
  useUppyEvent(ref, "files-added", (files) =>
    handleFilesAddedEvents(files, ref, props, (message) => {
      toast.error(message);
    })
  );

There are multiple Plugins being used, and how do i stop one being used for specific files?

lets say

image || Video < 50MB -> Xhr

video > 50MB -> Tus

I have tried This way of handling things but, it works, and uploads the Images and videos to specified endpoints, but throw’s error because one failed.


export function handleFilesAddedEvents(
  files: UppyFile<Meta, Record<string, never>>[],
  uppy: Uppy<Meta, Record<string, never>>,
  meta: TMetadatas,
  errorCb: (message: string) => void
) {
  files.map((item) => {
    let isVideo = allowedVideoTypes.includes(item.type);
    let isImage = allowedImageTypes.includes(item.type);
    let isUploadable = isVideo || isImage;

    if (!isUploadable) {
      errorCb(`${item.extension} is not supported.`);
      uppy.removeFile(item.id);
    }

    if (isVideo) {
      uppy.setFileState(item.id, {
        xhrUpload: undefined,
        tus: {
          endpoint: endpoints.uploader(
            `/uploads/v1/sign/video?relId=${meta.relationId}&visibility=${meta.visibility}`
          ),
          chunkSize: 150 * 1024 * 1024,
          retryDelays: [0, 3000, 5000, 10000, 20000],
          onBeforeRequest: (req) => {
            return new Promise((resolve) => {
              let xhr: XMLHttpRequest = req.getUnderlyingObject();
              if (req.getURL().includes(import.meta.env.VITE_BACKEND_URL)) {
                xhr.withCredentials = true;
                let token = sessionStorage.getItem("authToken");
                if (token) {
                  xhr.setRequestHeader("Authorization", token);
                }
              } else {
                xhr.withCredentials = false;
              }
              resolve(() => {});
            });
          },
        },
      });
      return;
    }
    uppy.setFileState(item.id, {
      xhrUpload: {
        endpoint: endpoints.uploader("/uploads/v1/sign/image"),
        formData: true,
        method: "POST",
        fieldName: "file",
        onBeforeRequest(xhr) {
          if (files[0] && allowedVideoTypes.includes(files[0].type)) {
            console.log("I have been called?");
            xhr.abort();
            return;
          }
          let token = sessionStorage.getItem("authToken");
          if (token) {
            xhr.setRequestHeader("Authorization", token);
          }
        },
      },
    });
  });
}

Writing a react story for a component using react hooks

I’m learning how to use react storybook. I’m trying to write a story for the GeneralDashboardSidebar component. However, nothing is being rendered on storybook. I’ve tried going over the docs no much help from there.

import React, { useState } from "react";
import { Link } from "react-router-dom";
import {
    DashboardSidebarContainer,
    SidebarTitle,
    BiSolidChevronLeftIcon,
    BiSolidChevronRighIcon,
    UserProfile,
    UserProfileDescription,
    BiSolidCircleIcon,
    SideBarLink,
    SideBarLinkContainer,
} from "./GeneralDashboardSidebarElements";
import { cdnContentImagesUrl } from "src/features/apiUrl";

const GeneralDashboardSidebar = ({ userDetail, sidebarItems }) => {
    const avatar = cdnContentImagesUrl("/user/" + (userDetail?.avatar || "avatar.png"));

    const [isOpen, setIsOpen] = useState(true);

    return (
        <DashboardSidebarContainer $isOpen={isOpen}>
            <UserProfile $isOpen={isOpen}>
                <Link to={`/user/${userDetail?.username}`}>
                    <div className="user-profile-image">
                        <img
                            style={{
                                width: "40px",
                                height: "40px",
                            }}
                            src={avatar}
                            alt={`${userDetail?.username} Profile Picture `}
                        />
                        <BiSolidCircleIcon />
                    </div>
                </Link>
                <UserProfileDescription $isOpen={isOpen}>
                    <h4>{userDetail?.name}</h4>
                    <span>@{userDetail?.username}</span>
                </UserProfileDescription>
            </UserProfile>

            <SideBarLinkContainer $isOpen={isOpen}>
                {sidebarItems.map((item) => (
                    <SideBarLink key={item.to} to={item.to} $isOpen={isOpen}>
                        {item.icon}
                        {isOpen && <SidebarTitle $isOpen={isOpen}> {item.label} </SidebarTitle>}
                    </SideBarLink>
                ))}
            </SideBarLinkContainer>

            <SideBarLink
                style={{
                    height: "50px",
                    position: "absolute",
                    bottom: "0",
                    left: "0",
                    width: "100%",
                    backgroundColor: "#2a2a2a",
                    display: "flex",
                    borderRadius: "0",
                    color: "#f5f5f5",
                }}
                $isOpen={isOpen}
                onClick={() => setIsOpen(!isOpen)}
            >
                {isOpen ? (
                    <>
                        <BiSolidChevronLeftIcon />
                        <SidebarTitle $isOpen={isOpen}> Collapse </SidebarTitle>
                    </>
                ) : (
                    <BiSolidChevronRighIcon />
                )}
            </SideBarLink>
        </DashboardSidebarContainer>
    );
};

export default GeneralDashboardSidebar;

The story I wrote:

import React, { useState } from "react";
import GeneralDashboardSidebar from ".";
import {
    BiHomeCircleIcon,
    PiNotebookDuotoneIcon,
    BiBookmarksIcon,
    BiChatIcon,
} from "src/components/Dashboard/DashbaordSidebar/DashbaordSidebarElements";
import { GiTridentShield } from "react-icons/gi";
import { FiSettings } from "react-icons/fi";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

export default {
    title: "Components/GeneralDashboardSidebar",
    component: GeneralDashboardSidebar,
    argTypes: {
        userDetail: {
            control: { type: "object" },
        },
        sidebarItems: {
            control: { type: "array" },
        },
    },
    decorators: [(Story) => <Router>{Story}</Router>],
};

const Template = (args) => {
    const [isOpen, setIsOpen] = useState(true);
    const handleOnClick = () => {
        setIsOpen(!isOpen);
    };

    return <GeneralDashboardSidebar {...args} $isOpen={isOpen} userDetail={userDetail} sidebarItems={sidebarItems} />;
};

export const OpenSidebar = {
    args: {
        userDetail: {
            name: "John Doe",
            username: "johndoe",
            avatar: "https://example.com/avatar.png",
        },
        sidebarItems: [
            { to: "/", icon: <BiHomeCircleIcon />, label: "Home" },
            { to: "/dashboard/reconage", icon: <GiTridentShield size={30} />, label: "Reconage" },
            { to: "/dashboard/notes", icon: <PiNotebookDuotoneIcon />, label: "Notes" },
            { to: "/dashboard/chat", icon: <BiChatIcon />, label: "Chat" },
            { to: "/dashboard/saved", icon: <BiBookmarksIcon />, label: "Saved" },
            { to: "/settings", icon: <FiSettings size={30} />, label: "Settings" },
        ],
    },
    render: (args) => <Template {...args} />,
};

export const ClosedSidebar = {
    args: {
        ...OpenSidebar.args,
    },
    render: (args) => <Template {...args} />,
};

nothing shows on storybook. What am I doing wrong? How can I go about doing it in a proper way. Any help offered would be appreciated.

Broken TikTok Embed Player on Mobile devices

I’m trying to embed videos into my website using iframes and https://developers.tiktok.com/doc/embed-player?enter_method=left_navigation.

When clicking any comments/like/share buttons on mobile devices iframe tries to automatically open TikTok app.

However, if you do not have it installed, instead it tries to open app store. This breaks the player with an error
Not allowed to launch ” because a user gesture is required.

Has anybody encountered this issue and has any workaround for it?

Tried setting different allow/sandbox attributes to iframe, didn’t seem to do anything.

Only options I see is to just put an invisible overlay to prevent users from clicking those buttons, which is stupid.

How to use [email protected] library for Clientside DOM manipulation in web worker?

I am currently try to optimize many-many html dom manipulation in frontend without using server due to small size of the server as well. I am interested to use this worker dom library tutorial to append Hello World heading as first trial.

import { upgrade } from 'https://unpkg.com/@ampproject/[email protected]/dist/worker.mjs';

upgrade(self).then(() => {
    function addHelloWorld() {
        const h1 = document.createElement('h1');
        h1.textContent = 'Hello World';
        document.body.appendChild(h1);
    }

    addHelloWorld();
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Worker DOM Example</title>
    <script src="https://unpkg.com/@ampproject/[email protected]/dist/index.mjs" type="module"></script>
    <script src="https://unpkg.com/@ampproject/[email protected]/dist/index.js" nomodule defer></script>
</head>
<body>
    <div id="primes"></div>
    <script type="module">
        import { upgradeElement } from 'https://unpkg.com/@ampproject/[email protected]/dist/index.mjs';

        window.addEventListener('load', async () => {
            try {
                await upgradeElement(document.getElementById('primes'), './worker.js');
                console.log('Worker DOM initialized');
            } catch (error) {
                console.error('Error initializing Worker DOM:', error);
            }
        });
    </script>
</body>
</html>

But why it still doesnt work? Previously I cant use same path just as the tutorial, now I cant see the Hello World heading in the webpage. Thank you for your attention.

Ref: https://www.jameslmilner.com/posts/worker-dom/

How to add spinner to ASP.net while processing

I am using ASP.net Web forms

I have users register into my page

once they registered a 3rd pty code updates the database which can take between 1 sec and few minutes

I want to add a rotating spinner wheel while server is running and waiting for the 3rd pty response.

there is a loop with waiting to check the for 3rd pty result

what i want, is to have a spinner that shows the user that there is a process running in the backend

I tried to add asp:image with spinning gif, but when i call it it does not show till the process is finished

i wonder if there is an easy way to add the spinner

here is my code for reg.aspx

<div>
<div>Register</div>
<div>
    <asp:TextBox ID="FirstName" runat="server" placeholder="First Name"></asp:TextBox>
</div>
<div>
    <asp:TextBox ID="LastName" runat="server" placeholder="Last Name"></asp:TextBox>
</div>
<div>
    <asp:TextBox ID="PhoneNumber" runat="server" placeholder="Phone Number"></asp:TextBox>
</div>
<div>
    <asp:TextBox ID="Email" runat="server" placeholder="Email" TextMode="Email"></asp:TextBox>
</div>
<div>
    <asp:TextBox ID="Password" runat="server" placeholder="Password" TextMode="Password"></asp:TextBox>
</div>
    <div>
    <asp:Label ID="ErrorMessage" runat="server" Visible="false" Text=""></asp:Label>
</div>
<div>
    <asp:Image runat="server" ID="imgSpin" ImageUrl="~/images/spinner6.gif" Visible="true" />
</div>                    

<asp:Button ID="registerButton" runat="server" Text="Sign Up" OnClick="registerButton_Click" />

</form>
</body>

and here for reg.aspx.cs

protected void registerButton_Click(object sender, EventArgs e)
{
    RegisterUser();
}

   protected void RegisterUser()
   {
       imgSpin.Visible = true;
       
       string firstName = FirstName.Text;
       string lastName = LastName.Text;
       string phoneNumber = PhoneNumber.Text;
       string email = Email.Text;
       string password = Password.Text;

       Reg(firstName, lastName, phoneNumber, email, password);
       string resultCode = "*";
       bool bExit = false;


       while (!bExit)
       {
           switch (resultCode.ToUpper())
           {
               case "ERROR":
                   ErrorMessage.Text = "Invalid user ID or password. Please try again.";
                   ErrorMessage.Visible = true;
                   bExit = true;
                   break;


               case "OK":
                   Response.Redirect("job.aspx");
                   bExit = true;
                   break;

               default:
                   // Wait 2 seconds, then call the procedure again
                   System.Threading.Thread.Sleep(2000);
                   resultCode = Call3Pty(); 
                   break;
           }
       }

       imgSpin.Visible = false;
   }

GPT suggested adding 2 event to the Signup button but that never works, only client side gets triggered but the backend never did

<asp:Button ID="registerButton" runat="server" Text="Sign Up" OnClick="registerButton_Click" OnClientClick="showSpinner();" />

how can i add a simple spinner while my code running in the background

Why is Vue Router looking for a param when the current route doesn’t have one?

My app has the following routes in Vue Router:

const routes = [
  {
    path: '/',
    name: 'home'
  },
  {
    path: '/about',
    name: 'about',
    component: About
  },
  {
    path: '/store',
    name: 'store',
    component: Store
  },
  {
    path: '/profile/:id',
    name: 'profile',
    component: Profile
  }
]

When I navigate to a profile page with an id in the url it works fine, but when I navigate to any other page I keep getting the following error:

Error: Missing required param "id"

Any idea why this is happening? Why would Vue Router keep looking for the id param even in routes that do not require the id param?

Page breaks while replying in Nested Comments

I’m creating a Nested Comments app in React. While adding comment in the parent node works fine but, replying to that same node breaks the page. The children nodes doesn’t work fine. Here’s the explanation of the code below.

Comment.js

const onAddComment = () => {
    if (editMode) {
      handleEditMode(comments.id, inputRef?.current?.innerText);
    } else {
      console.log("DATA HERE", comments.id, input);
      setExpand(true);
      handleInsertNode(comments.id, input); <-- this function breaks the page
      setShowInput(false);
      setInput("");
    }
  };

return (
...
<Action type="REPLY PARENT" handleClick={onAddComment} />
...
)

App.js

const [commentsData, setCommentsData] = useState(comments);
const { insertNode, editNode, deleteNode } = useNode(); <-- this is custom hook created

const handleInsertNode = async (commentId, comment) => {
    console.log("HandleInsertNode Func", commentsData);
    const finalTree = await insertNode(commentsData, commentId, comment);
    setCommentsData(finalTree);
  };

useNode

const insertNode = (tree, commentId, item) => {
    if (tree.id === commentId) {
      tree?.items?.push({
        id: new Date().getTime(),
        name: item,
        items: [],
      });
      return tree;
    }

    let latestNode = [];
    latestNode = tree?.items?.map((newItems) => {
      return insertNode(newItems, commentId, item);
    });

    return { ...tree, items: latestNode };
  };

Although thouroughly tested, but, still error persists. The ‘REPLY PARENT’ button works exactly like ‘COMMENT’ button, but, while clicking on it throws error as ‘handleInsertNode is not a function and has same common onAddComment function’. What could be the obvious error, which I’m unable to detect. Here’s the link to sandbox –> https://codesandbox.io/p/sandbox/nested-comments-app-52jdsh

I cannot get my ‘put’ request to work correctly (or at all) in my Node.js server and am struggling to understand why not?

The problem is that my PUT request is not responding when I try to trigger it via my client-side Javascript event listener. My get and post requests are, yet my put is not and they are assigned to the same path endpoint.

I am trying to console.log the request in my put request into the terminal’s console log.

Here is the server side code:

app.get('/', (req, res) => {
            const cursor = db.collection('quotes').find()
            quotesCollection
            .find()
            .toArray()
            .then(results => {
                res.render('index.ejs', {quotes: results})
                console.log('get request works')
                
            }).catch(error => console.error(error))
            
        })
app.put('/quotes', (req,res) => {
            console.log(req.body, 'hello')
        })

I am trying to have my button eventListener trigger my PUT request via fetch()

Here is my client-side code:

const update = document.querySelector('#update-button')

update.addEventListener('click', _ => {
    fetch('/quotes', {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            name: 'Darth Vader',
            quote: 'I find your lack of faith disturbing.',
        }),
    })
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(error => console.error(error))
})

How do I update the directions of a map in javascript using Google maps api

I am not react or angular or any of those, flat out javascript.

So I have a file that will pull a random address from the database. I haven’t had luck but what I want to do is take that address and display it as the origin in the map. Any time I generate, it’ll pull a different address and I want it to re-render that new address. I have tried getters and setters, I have tried nearly anything I can think of, but I’m sure I’m overthinking.

The end result every time is as expected or else I wouldn’t ask; nothing.

I set up CORS in my backend minimal API and I have issues fetching data from the React frontend

As the title says, I set up a minimal WEB API in .NET8 with CORS, and the routes seem to be working fine on the backend, and even tested the CRUD operations with the REST Client extension in VSCode.

When I tried to fetch from one of the routes and log the data on the console, I get this error instead:

Access to fetch at ‘http://localhost:5050/words’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Below is the code for the React component which fetches from the route:

import { useEffect } from "react"

const NewWord = () => {

    const submitHandler = async() => {
        try {
            const response = await fetch("http://localhost:5050/words")
            const data = await response.json()
            console.log(data)
        } catch (error) {
            console.error(error)
        }
    }

  return (
    <>
        <h1 className="text-center text-bold text-white">New Word</h1>
        {/* Major container */}
        <div className="">
            {/* Container */}
            <div className="border border-solid p-4 my-4 rounded-xl bg-green-300">

                {/* Word */}
                <div className=" p-2">
                    <input type="text" name="" id="" 
                    placeholder="Word" 
                    className="w-full"/>
                </div>

                {/* Definition */}
                <div className="p-2">
                    <input type="text" 
                    name="" id="" 
                    placeholder="Type your definition here..."
                    className="w-full" />
                </div>

                {/* Example */}
                <div className="p-2">
                    <input type="text" 
                    name="" id="" 
                    placeholder="Example sentence..." 
                    className="w-full"/>
                </div>

                {/* Tags */}
                <div className="p-2">
                    <input type="text" 
                    placeholder="Type a list of comma-separated tags..."
                    className="w-full" />
                </div>

                {/* Language */}
                <div className="p-2">
                    <select name="" id="">
                        <option value="english">English</option>
                        <option value="hausa">Hausa</option>
                        <option value="french">French</option>
                        <option value="arabic">Arabic</option>
                        <option value="wolof">Wolof</option>
                        <option value="zulu">Zulu</option>
                        <option value="swahili">Swahili</option>
                        <option value="igbo">Igbo</option>
                        <option value="xhosa">Xhosa</option>
                    </select>
                </div>

                <div className="mt-2 flex justify-center">
                    <button 
                    className="border-4 rounded-xl p-2 w-full font-bold"
                    onClick={submitHandler}>
                        Submit
                    </button>
                </div>
            </div>


        </div>


    </>
    
  )
}

export default NewWord

and the minimal API:

using AUB_backend;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// DbContext configuration
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));


// CORS configuration
builder.Services.AddCors(options => {
    options.AddPolicy("AllowSpecificOrigin", builder =>
    {
        builder.WithOrigins("http://localhost:3000")
            .AllowAnyMethod()
            .AllowAnyHeader();
    });
});

var app = builder.Build();

// enable CORS
app.UseCors("AllowSpecificOrigin");
app.UseRouting();

// default page
app.MapGet("/", () => "API Default Page");


// CRUD actions

// CREATE a new word
app.MapPost("/words", async(AppDbContext DbContext, Word newWord) => {
    DbContext.Words.Add(newWord); // add new word to db
    await DbContext.SaveChangesAsync(); // save changes to db asynchronously
    return Results.Created($"/words/{newWord.Id}", newWord);
});

// READ all words
app.MapGet("/words", async(AppDbContext DbContext) => {
    var words = await DbContext.Words.ToListAsync(); // fetch words from db
    return Results.Ok(words);
});

// READ an existing word by Id
app.MapGet("/words/{id}", async(AppDbContext DbContext, int id) => {
    var word = await DbContext.Words.FindAsync(id); // fetch word from db using Id

    if (word is not null)
    {
        return Results.Ok(word);
    }
    else
    {
        return Results.NotFound();
    }
});

// UPDATE a word
app.MapPut("/words/{id}", async(AppDbContext DbContext, int id, Word updatedWord) =>
{
    var word = await DbContext.Words.FindAsync(id);
    if (word is null)
    {
        return Results.NotFound();
    }

    // update word properties
    word.Term = updatedWord.Term;
    word.Definition = updatedWord.Definition;
    word.Example = updatedWord.Example;
    word.Tags = updatedWord.Tags;
    word.Language = updatedWord.Language;

    await DbContext.SaveChangesAsync(); // save changes to db
    return Results.Ok(word);
});

// DELETE an existing word
app.MapDelete("words/{id}", async(AppDbContext DbContext, int id) => {
    var word = await DbContext.Words.FindAsync(id); // find word by Id
    if (word is null)
    {
        return Results.Ok(word);
    }

    DbContext.Words.Remove(word); // remove word from db
    await DbContext.SaveChangesAsync(); // save changed
    return Results.NoContent(); // return a 204 response (No Content)

});

app.Run();

How does the truthiness of null == 0 (false), null > 0 (false), null >= 0 (true) make sense? [duplicate]

I’ve seen a lot of the “haha js truthiness is wacky” examples over the years, but I just came across this one and I’m scratching my head:

  • null == 0 (false)
  • null > 0 (false)
  • null >= 0 (true!)

Even if we’re coercing null to be 0 in the last one (>=), why isn’t it being coerced in the first one (==)?

(I performed these operations in Chrome inspector console, if that perhaps changes anything)

How can I make my scrolling smooth like the attached website?

Currently, I’ve tried the html {scroll-behavior: smooth;} addition to my global style file but it is no where near the extent of smooth scrolling featured here: https://fireart.studio/blog/20-best-futuristic-website-examples-to-inspire-you/

It seems to have some sort of momentum to it and is therefore not choppy like a regular scroll bar. I have also noticed it’s quite moderate in speed compared to if I were to scroll as fast as I can on a regular scroll bar, which could be a second component to why it feels so smooth.

I’ve looked through a few other answers and I haven’t been able to find how to do the scrolling specifically like this. I appreciate any advice/insight.

When fetching HTML all sources are invalid (HTML/JAVASCRIPT)

So, I was making an HTML fetcher that gets HTML from a URL using fetch(). Everything was going well until I got to the part of displaying the HTML. Everything was fine until you look at the images, links, exc. Instead of going to that URL on the website, it went to that path on my computer. Any way to fix this? Thanks in advance.

<html>
<head>
    <title>TWN'S TOOLS: Unblk</title>
</head>
<body>
    <div class="main">
        <div class="top">
            <input type="text" id="inputbar"></input>
            <button onclick="load()">Load</button>
        </div>
        <iframe id="box"></iframe>
    </div>
</body>
<style>
    .top{
        display: flex;
        input{
            width: 100%;
        }
    }
    iframe{
        width: 100%;
        height: 97%;
    }
    body{
        margin: 0;
        padding: 0;
    }
    .main{
        width: 100%;
    }
    html{
        text-align: center;
    }
</style>
<script>
    async function load(){
        const url = document.querySelector("#inputbar").value;
        let que = await fetch('https://corsproxy.io/?'+encodeURIComponent(url));
        const promise = await que;
        let stat = await promise.status;
        stat = await stat.toString();
        que = await que.text();
        let box = document.querySelector("#box");
        if(stat === "200"){
            box.contentDocument.write(que);
        }else{
            box.contentDocument.write("<h1>Status code "+status+"</h1>");
        };
        fix();
    };
</script>

Regex match pattern result in a single line instead of array

So I have the current code which I wrote

let css = `
flexGrow:1 backgroundColor:$baC-transparent maxWidth:1601 eq_last:{flexGrow:-1 backgroundColor:$baC-transparent maxWidth:1601} eq_0:{flexGrow: 0 backgroundColor:$baC-transparent maxWidth:1601} eq_1:{flexGrow:1 backgroundColor:$baC-transparent maxWidth:1601 eq_0:{kasd}} 
`
//css = css.replace(/eq_/g, "neq_")
let match = css.match(/eq_(.*)({)(.*)(})/g);
console.log(match)

The issue is with the result, notice that I have the string in a single line and match return the whole thing in a single line

I need the current resullt

[
eq_last:{flexGrow:-1 backgroundColor:$baC-transparent maxWidth:1601},
eq_0:{flexGrow: 0 backgroundColor:$baC-transparent maxWidth:1601},
eq_1:{flexGrow:1 backgroundColor:$baC-transparent maxWidth:1601 eq_0:{kasd}},
]

I want the match to ignore inner eq_0 and return the above result.

any solution with regex or otherwise are will come, but it has to be fast.