Load or type music notes on textarea and Increase them onclick

var notes = ['do', 'do#', 're', 're#', 'mi', 'fa', 'fa#',
  'sol', 'sol#', 'la', 'la#', 'si'
];

function stepUp() {
  var text = document.getElementById('textarea');
  if (typeof text.count == 'undefined') {
    text.count = 0;
  } else {
    text.count++;
  }

  if (text.count == notes.length) {
    text.count = 0;
  }
  text.innerHTML = notes[text.count];
}

function stepDown() {
  var text = document.getElementById('textarea');
  text.count--;

  if (text.count == notes.length) {
    text.count = 0;
  }

  if (text.count < 0) {
    text.count = 11;
  }
  text.innerHTML = notes[text.count];
}

/* Load file*/
function load_song() {
  var fileToLoad = document.getElementById("load_button").files[0];
  var fileReader = new FileReader();
  fileReader.onload = function(fileLoadedEvent) {
    var textFromFileLoaded = fileLoadedEvent.target.result;
    document.getElementById("textarea").value = textFromFileLoaded;
  };
  fileReader.readAsText(fileToLoad, "UTF-8");
}
body {
  font-family: Arial, sans-serif;
  background-color: #333;
  color: #ddd;
  text-align: center;
}

container {
  display: flex;
  margin: 2vmin;
  position: relative;
  top: 3vmin;
}
<div class="container">
  <textarea id="textarea" rows="5" cols="50">---</textarea>
</div>

<button onclick="stepUp()" class="stepUp_Button">Up</button>
<button onclick="stepDown()" class="stepDown_Button">Down</button>

<!-- Load button -->
<span>Load File:&nbsp;</span>
<input type="file" id="load_button">
<button class="load_button" onclick="load_song()">Load</button>

I would like to write in the textarea in random order the notes

"do do# re re# mi fa fa# sol sol# la la# si"

(or upload a .txt file with these notes written in random order
sol mi do# fa si etc)

and pressing the up button to raise them all +1,
i.e. do => do#
and by pressing the down button to decrease them all -1. do => si

While it seems to work for one note,
if I write in the textarea and press the up button it does not work at all, just as it does not work if I upload a simple .txt file.
Any ideas would be extremely helpful. Thanks!

Locally networked games

Background

I am looking to write card games that can be played at friends houses for game night. Ideally what I want to do is be able to have some sort of website that can be saved offline. When you go to the site, you can setup a local connection between phones (ideally Bluetooth, but also WIFI would work) that makes it easy to let people play games like poker with their phones if we forget a set of cards

Additional Context

I want to avoid servers because we sometimes camp in the forest and there’s no connections out there, but if I have to do it over wifi I can bring a portable router.

So the flow for the app would be that 1 person sets up a “session/lobby”, then other players can join with a join code (maybe the bluetooth pairing code?), and they are connected directly to one another for the duration of the game. I don’t care about persisting any data, all of it will be in-memory and each “session/lobby” can be considered independent.

What I need to know

I know I would need a service worker to setup an offline website for this, but what can I use to do the “local” connection portion? Is Bluetooth the best/only option? or is there another connection standard that is browser-accessible that would work better? I don’t even know the terminology to begin looking into alternatives for this sort of a setup, so any advice would be great.

How to improve handwriting recognition in an image

enter image description here

I’m trying to develop a system to read the handwriting in a chart within a written page, using a multimodal LLM. I’m using Google apps script So far I’ve experimented:

function openRouterApiRequest() {
  var apiKey = "****";


    var imageUrl = "https://www.dropbox.com/scl/fi/xxeyyiqs74rip0319080a/output-onlinepngtools.png?rlkey=******&e=2&st=w21t3k3j&raw=1";

  var apiEndpoint = 'https://openrouter.ai/api/v1/chat/completions';

  var payload = {
    "model": "meta-llama/llama-4-maverick",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            // "text": "can you reproduce the chart in the middle of the image?"
            "text": " In the role of an OCR program can you convert the entire page from text and handwriting into text? Please note that in the chart in the middle of page, the 4th column has options of : S or M or C only. Also the only options for the 5th Column  are 'up pointing arrow', 'down pointing arrow' or '='. The 6th column has only Y or N as options"
          },
          {
            "type": "image_url",
            "image_url": {
              "url": imageUrl
            }
          }
        ]
      }
    ]
  };

  var options = {
    'method': 'post',
    'headers': {
      'Authorization': 'Bearer ' + apiKey,
      'Content-Type': 'application/json'
    },
    'payload': JSON.stringify(payload),
    'muteHttpExceptions': true // To get the response even if the request fails
  };

  var response = UrlFetchApp.fetch(apiEndpoint, options);
  var responseCode = response.getResponseCode();
  var responseBody = response.getContentText();

  // Handle the response as needed
  Logger.log('Response Code: ' + responseCode);
  Logger.log('Response Body: ' + responseBody);

  // You might want to parse the responseBody if it's JSON
  try {
    var jsonResponse = JSON.parse(responseBody);
    Logger.log(jsonResponse);
  } catch (e) {
    Logger.log('Failed to parse response as JSON: ' + e.message);
  }
}

Only about half of the of the cells are accurately detected in my current setup. I’m wondering about preprocessing the images to improve handwriting contrast. I tried manually increasing the contrast with https://onlinepngtools.com/change-png-quality and saving the image. However after doing this I don’t see a significant improvement in character recognition. How can I improve the contrast further using an image processing library to improve recognition?

How to use SoundEffect in JavaScript

I was making a Tic Tac Toe game using React and adding sound effects for moves, wins, and draws. I’ve created functions like playWinSound, playDrawSound, and playMoveSound in SoundEffects.js file, and then imported them into Game.js file. However, when I try to call the function, the error ‘was declared but never used’ appears. How do I fix this issue so that the voice function can work correctly in React? Are there any specific rules on how to export and import functions in React?

how to select from the menu if the select is react-select

how to select from the menu if the select is react-select instead of the normal html select:
this is how typically the react-select is implemented:

<div class="flex flex-col space-y-1 ">
<p class="font-semibold">Volume <span class="text-red">*</span></p>
<div class="text-emdmsPrimary  placeholder:text-N95 placeholder:text-sm    focus:border-emdmsPrimary focus:ring-emdmsPrimary w-3/4 rounded-md css-b62m3t-container">
<span id="react-select-2-live-region" class="css-7pg0cj-a11yText"></span>
<span aria-live="polite" aria-atomic="false" aria-relevant="additions text" role="log" class="css-7pg0cj-a11yText"></span>
<div class=" css-vfyfn6-control">
<div class=" css-hlgwow"><div class=" css-9nn9n2-placeholder" id="react-select-2-placeholder">Select...</div><input id="react-select-2-input" tabindex="0" inputmode="none" aria-autocomplete="list" aria-expanded="false" aria-haspopup="true" role="combobox" aria-activedescendant="" aria-readonly="true" aria-describedby="react-select-2-placeholder" class="css-1hac4vs-dummyInput" value="">
</div>
<div class=" css-1wy0on6">
<span class=" css-1u9des2-indicatorSeparator"></span>
<div class=" css-1xc3v61-indicatorContainer" aria-hidden="true">
<svg height="20" width="20" viewBox="0 0 20 20" aria-hidden="true" focusable="false" class="css-8mmkcg"><path d="M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747 3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0 1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502 0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0 0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z"></path></svg>
</div>
</div>
</div>
<input name="volume_id" type="hidden" value="">
</div>
</div>

Why does async/await sometimes lead to slower execution than raw Promises? [closed]

I’ve been working with JavaScript for a while and often prefer using async/await for readability. However, I recently ran into a situation where switching to raw Promises (using .then) actually improved performance in a tight loop of async operations.

Why does this happen?
Is there a known overhead in the way async/await is handled under the hood compared to plain Promises?

I’m optimizing a data-fetching flow where hundreds of async calls are made in sequence or parallel, and curious about the most efficient approach in such cases.

Would love to hear from others who faced similar trade-offs.

Setting Javascript Variable within a Javascript Variable

I hope this makes sense to someone. Not even sure this is possible so that’s why I’m posting a question here.

I’m returning the data in Fetched Data using the Fetch shown in Fetching the Data. I’m dynamically building a Radio Button from the Fetched Data as shown in Fetching the Data for the Form.

“radioDecision += <input type="radio" id="decision" name="decision" class="form-check-input" value="${value.CODE}" required> ${value.DESCRIPTION}<br/>

Within Javascript Varibles and HTML Form Elements you can see that I’m setting ${decision_selection_1} so it’s checked if “decision” has a value of “N”. It actually could be “N” or “Y” but I set it to “N” for this example.

<input type=”radio” id=”decision” name=”decision” class=”form-check-input” value=”N” ${decision_selection_1} required>

<input type=”radio” id=”decision” name=”decision” class=”form-check-input” value=”Y” ${decision_selection_2} required>

My question:
How can I set ${decision_selection_1} or ${decision_selection_2} to show “checked” if “decision” has been set to “N” or “Y” after the Radio Button has been dynamically created?

The variable “decision” is being set after the Fetch statement builds the radio buttons. In Radio Buttons after Fetch, one of the Radio Buttons should be “checked” if “decision” has been set to “N” or “Y”.

Fetched Data:

[
  {
    "ROW_NUMBER": 1,
    "DATA_CODE": "Decision",
    "CODE": "N",
    "DESCRIPTION": "Reviewed Comment, No Response Required"
  },
  {
    "ROW_NUMBER": 2,
    "DATA_CODE": "Decision",
    "CODE": "Y",
    "DESCRIPTION": "Response Entered Below"
  }
]

Fetching the Data:

let radioDecision;

fetch('URL', options)
  .then(response => response.json())
  .then(data => {
     Object.entries(data).forEach(([key, value]) => {
       radioDecision += `<input type="radio" id="decision" name="decision" class="form-check-input" value="${value.CODE}" required> ${value.DESCRIPTION}<br/>`
     });
  })
  .catch((error) => {
     toastr["error"]("Something went wrong.", "Error");
  });

Javascript Varibles and HTML Form Elements

let decision_selection_1;
let decision_selection_2;

decision = 'N';

decision_selection_1 = decision == "N" ? "checked" : "";
decision_selection_2 = decision == "Y" ? "checked" : "";                                 

<div class="form-check">
      <input type="radio" id="decision" name="decision" class="form-check-input" value="N" ${decision_selection_1} required>
      Review Comment, No Response Required
</div>
<div class="form-check">
     <input type="radio" id="decision" name="decision" class="form-check-input" value="Y" ${decision_selection_2} required>
     Response Entered Below
     <div class="valid-feedback">Completed!</div>
     <div class="invalid-feedback">Please make a selection.</div>
 </div>

View Source:
<div class="form-check">
  <input type="radio" id="decision" name="decision" class="form-check-input" value="N" checked required=""> Reviewed Comment, No Response Required
<br>
  <input type="radio" id="decision" name="decision" class="form-check-input" value="Y" required=""> Response Entered Below<br>
  <div class="valid-feedback">Completed!</div>
  <div class="invalid-feedback">Please make a selection.</div>
</div>

Radio Buttons after Fetch

<div class="form-check">
  ${radioDecision}
  <div class="valid-feedback">Completed!</div>
  <div class="invalid-feedback">Please make a selection.</div>
</div>

View Source:
<div class="form-check">
  <input type="radio" id="decision" name="decision" class="form-check-input" value="N" required=""> Reviewed Comment, No Response Required
<br>
  <input type="radio" id="decision" name="decision" class="form-check-input" value="Y" required=""> Response Entered Below<br>
  <div class="valid-feedback">Completed!</div>
  <div class="invalid-feedback">Please make a selection.</div>
</div>

Lock vertical scroll of a parent when horizontally swiping a child

I am writing a hook that will allow me to listen for swipe actions on an element. Problem is that I get an annoying vertical pull drag when trying to swipe horizontally. I’ve managed to achieve the desired behavior by locking vertical scroll of the parent after detecting that horizontal swipe moved 5px left or right.

But I get this in the console when trying to scroll the element:
[Intervention] Ignored attempt to cancel a touchmove event with cancelable=false, for example because scrolling is in progress and cannot be interrupted.
I tried checking for truthy e.cancelable but then the hook stops working.
How can I fix this?

Here’s the hook:

import { useRef } from "react";

export const useSwipe = () => {
  const touchStartX = useRef<number | null>(null);
  const touchEndX = useRef<number | null>(null);
  const touchStartY = useRef<number | null>(null);
  const touchEndY = useRef<number | null>(null);

  const minSwipeDistance = 100;

  const box = document.getElementById("scrollable-cards-box");

  const cancelTouch = (e: TouchEvent) => e.preventDefault();

  const onTouchStart = (e: React.TouchEvent) => {
    touchEndX.current = null;
    touchEndY.current = null;
    touchStartX.current = e.targetTouches[0].clientX;
    touchStartY.current = e.targetTouches[0].clientY;
  };

  const onTouchMove = (e: React.TouchEvent) => {
    touchEndX.current = e.targetTouches[0].clientX;
    touchEndY.current = e.targetTouches[0].clientY;

    if (!touchStartY.current || !touchEndY.current) return;
    if (!touchStartX.current || !touchEndX.current) return;
//something here causes the error
    if (
      touchEndX.current > touchStartX.current + 5 || 
      touchEndX.current < touchStartX.current - 5
    ) {
      if (box) {
        box.addEventListener("touchmove", cancelTouch, {
          passive: false,
        });
        box.style.touchAction = "none";
        console.log("set touch to none");
      }
    }
  };

  const onTouchEnd = () => {
    if (!touchStartX.current || !touchEndX.current) return;
    const distanceX = touchStartX.current - touchEndX.current;
    const isLeftSwipe = distanceX > minSwipeDistance;
    const isRightSwipe = distanceX < -minSwipeDistance;
    if (box) {
      box.style.touchAction = "auto";
      console.log("set touch to autoo");
      box.removeEventListener("touchmove", cancelTouch);
    }
    if (isRightSwipe) return "right";
    if (isLeftSwipe) return "left";
  };

  return { onTouchStart, onTouchMove, onTouchEnd };
};

I use returned functions on the child element props of the same name and add an event listener to the parent.

MudBlazor MudMenu not opening on ChangePassword page in Blazor Server with ASP.NET Core Identity

I am developing a Blazor Server application based on .NET 9 that uses ASP.NET Core Identity. The identity components (like ChangePassword) are coming from the MudBlazor template. Now, for some reasone, when I navigate to /Account/Manage/ChangePassword, my MudMenu in the AppBar doesn’t open anymore. After navigation to back to Home it starts working again….

Things I have tried before.

  • Added the ProfileMenu component to another site where it works. However, there it’s not part of the AppBar anymore
  • Removing the outer MudMenu elements and only keep MudNavMenu

Even if I comment everything inside ChangePassword.razor the issue persists, which makes me think the culprit is not the ChangePassword site itself, but somewhere else.

I am lost here… any help is much appreciated.

App.razor

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

<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <base href="/"/>
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet"/>
  <link href=@Assets["_content/MudBlazor/MudBlazor.min.css"] rel="stylesheet"/>
  <ImportMap/>
  <HeadOutlet @rendermode="PageRenderMode"/>
</head>

<body>
<Routes @rendermode="PageRenderMode"/>
<script src="_framework/blazor.web.js"></script>
<script src=@Assets["_content/Extensions.MudBlazor.StaticInput/NavigationObserver.js"]></script>
<script src=@Assets["_content/MudBlazor/MudBlazor.min.js"]></script>

</body>

</html>

@code {

  [CascadingParameter]
  private HttpContext HttpContext { get; set; } = default!;

  private IComponentRenderMode? PageRenderMode =>
    HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null;

}

MainLayout.razor

@using MyApplication.Web.Components.Navbar
@inherits LayoutComponentBase

<MudThemeProvider/>
<MudPopoverProvider/>
<MudDialogProvider/>
<MudSnackbarProvider/>

<MudLayout>
  <AppBar/>
  <MudMainContent>
    @Body
  </MudMainContent>
</MudLayout>
...

AppBar.razor

<MudAppBar Fixed="false">
  <MudStack Row="true" Justify="Justify.FlexEnd" AlignItems="AlignItems.Center" Style="width: 100%">
    ...
    @if (IsAuthenticated)
    {
      <ProfileMenu/>
    }
  </MudStack>
</MudAppBar>

@code {
  public bool IsAuthenticated { get; set; }

  [Inject]
  public AuthenticationStateProvider? AuthenticationStateProvider { get; set; }

  [Inject]
  public ILogger<AppBar> Logger { get; set; }

  protected override async Task OnInitializedAsync()
  {
    var state = await AuthenticationStateProvider?.GetAuthenticationStateAsync()!;
    IsAuthenticated = state.User.Identity!.IsAuthenticated;
    Logger.LogInformation($"Authentication state: {IsAuthenticated}");
  }

}

ProfileMenu.razor

<MudMenu StartIcon="@Icons.Material.Outlined.AccountCircle"
         Label="Mein Profil"
         FullWidth="true"
         Variant="Variant.Outlined"
         Color="Color.Tertiary">
  <MudNavMenu>
    <MudNavLink Href="/favorites" Icon="@Icons.Material.Outlined.FavoriteBorder">Merkliste</MudNavLink>
    <MudNavLink Href="/my-ads" Icon="@Icons.Material.Filled.PostAdd">Meine Inserate</MudNavLink>
    <MudNavGroup Href="/Account/Manage" Title="Profile bearbeiten" Icon="@Icons.Material.Filled.Settings">
      <MudNavLink Href="/Account/Manage/ChangePassword" Icon="@Icons.Material.Outlined.Lock">Kennwort ändern
      </MudNavLink>
      <MudNavLink Href="/Account/Manage/Email" Icon="@Icons.Material.Outlined.Mail">Mail Addresse ändern
      </MudNavLink>
    </MudNavGroup>
    <MudNavLink Href="/Account/Logout" Icon="@Icons.Material.Filled.Logout">Ausloggen</MudNavLink>
  </MudNavMenu>
</MudMenu>

ChangePassword.razor

@page "/Account/Manage/ChangePassword"

@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Identity
@using MyApplication.Infrastructure.Identity
@using MyApplication.Web.Components.Layout
@using MudBlazor.StaticInput
@using MyApplication.Web.Components.Navbar

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject IdentityUserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject ILogger<ChangePassword> Logger

<PageTitle>Change password</PageTitle>

<MudContainer MaxWidth="MaxWidth.Small">
  <MudText Typo="Typo.h6" GutterBottom="true">Kennwort ändern</MudText>

  <EditForm Model="Input" FormName="change-password" OnValidSubmit="OnValidSubmitAsync" method="post">
    <DataAnnotationsValidator/>

    <MudGrid>
      <MudItem md="12">
        <MudStaticTextField For="@(() => Input.OldPassword)" @bind-Value="Input.OldPassword" Variant="_variant"
                            InputType="InputType.Password"
                            Label="Kennwort" Placeholder="Kennwort" HelperText="Bitte altes Kennwort eingeben."
                            UserAttributes="@(new() { { "autocomplete", "current-password" }, { "aria-required", "true" } })"/>
      </MudItem>
      <MudItem md="12">
        <MudStaticTextField For="@(() => Input.NewPassword)" @bind-Value="Input.NewPassword" Variant="_variant"
                            InputType="InputType.Password"
                            Label="Neues Kennwort" Placeholder="Neues Kennwort"
                            HelperText="Bitte neues Kennwort eingeben."
                            UserAttributes="@(new() { { "autocomplete", "new-password" }, { "aria-required", "true" } })"/>
      </MudItem>
      <MudItem md="12">
        <MudStaticTextField For="@(() => Input.ConfirmPassword)" @bind-Value="Input.ConfirmPassword" Variant="_variant"
                            InputType="InputType.Password"
                            Label="Neues Kennwort" Placeholder="Kennwort bestätigen"
                            HelperText="Bitte neues Kennwort erneut eingeben."
                            UserAttributes="@(new() { { "autocomplete", "new-password" }, { "aria-required", "true" } })"/>
      </MudItem>
      <MudItem md="12">
        <MudStaticButton Variant="Variant.Filled" Color="Color.Primary" FullWidth="true" FormAction="FormAction.Submit">
          Kennwort aktualisieren
        </MudStaticButton>
      </MudItem>
      <MudItem md="12">
        <StatusMessage Message="@message"/>
      </MudItem>
    </MudGrid>
  </EditForm>
</MudContainer>

@code {
 ...

}

0x, the flame graph generator tool for node, is missing a lot of data in the generated flame graph

I’m trying to profile my heap implementation, so I’ve created this script:

class BinaryHeap {
    array;
    comparator;

    constructor(comparator) {
        this.array = [];
        this.comparator = comparator;
    }

    static getParentIndex(index) {
        return (index - 1) >> 1;
    }

    static getLeftChildIndex(index) {
        return 2 * index + 1;
    }

    static getRightChildIndex(index) {
        return 2 * index + 2;
    }

    #swap(index1, index2) {
        [this.array[index1], this.array[index2]] = [
            this.array[index2],
            this.array[index1],
        ];
    }

    #compare(index1, index2) {
        return this.comparator(this.array[index1], this.array[index2]);
    }

    siftDown(index) {
        const value = this.array[index];

        const end = BinaryHeap.getParentIndex(this.array.length - 1);
        while (index <= end) {
            let left = BinaryHeap.getLeftChildIndex(index);
            let right = BinaryHeap.getRightChildIndex(index);
            let childIndex =
                right >= this.array.length || this.#compare(left, right) < 0
                    ? left
                    : right;

            if (this.comparator(value, this.array[childIndex]) < 0) break;
            this.array[index] = this.array[childIndex];
            index = childIndex;
        }

        this.array[index] = value;
    }

    siftUp(index) {
        const value = this.array[index];

        let parentIndex = BinaryHeap.getParentIndex(index);
        while (
            parentIndex >= 0 &&
            this.comparator(this.array[parentIndex], value) > 0
        ) {
            this.array[index] = this.array[parentIndex];
            index = parentIndex;
            parentIndex = BinaryHeap.getParentIndex(index);
        }

        this.array[index] = value;
    }

    pop() {
        if (this.array.length === 0) return;
        if (this.array.length === 1) return this.array.pop();

        this.#swap(0, this.array.length - 1);
        const value = this.array.pop();
        this.siftDown(0);

        return value;
    }

    push(item) {
        this.array.push(item);
        this.siftUp(this.array.length - 1);
    }
}

function compareFn(a, b) {
    return a - b;
}
const heap = new BinaryHeap(compareFn);

for (let i = 0; i < 10_000_000; i++) { heap.push(i) }
for (let i = 0; i < 10_000_000; i++) { heap.pop() }

and then profile it with the command using 0x as suggested by the Node.js – creating a flamegraph documentation page

0x -o heap.js

but the resulting flame graph seems to be missing a lot of samples. The push, pop, siftUp and siftDown functions are only sampled once, or sometimes 0 times out of 102 samples. Where did the other 100-102 samples go? And what is the big *(anonymous) block that got sampled 84 times?

Screenshot of flame graph generated.

Moving the code over to a HTML file and then using the built-in chrome performance profiler I get a much more detailed visualization without as much missing data. This is what I want from 0x too.

Screenshot of profiling using chrome devtools

Random website page javascript where some links open in a new window

I am trying to have a button that takes visitors to a random page on my website. Some of the links are in an iframe, while others need to show up in a new window.
This is what I have so far, but the code is not working yet, and I ‘m not sure how/if the iframe thing would work.

function randomPage() {
var urls = new Array();
urls[0] = "/index.html";
urls[1] = "/about";
urls[2] = "/virtualpets.html";
urls[4] = "/bestiary.html";
urls[5] = "/shrimp.html";
urls[6] = "/links.html";
urls[7] = "/coding.html";
urls[8] = "/hoard.html";
urls[9] = "/curios.html";
urls[10] = "/reading.html";
urls[11] = "/misc.html";
urls[12] = "/hellenicpaganism.html";
urls[13] = "/heathenry.html";
urls[14] = "/kemeticism.html";
urls[15] = "/baltic.html";
urls[16] = "/updates.html";
urls[17] = "/now.html";
urls[18] = "/shrines.html";
urls[19] = "/fanlistings.html";
urls[20] = "/shrines/nidai/";
urls[21] = "/shrines/tsumugi/";
urls[22] = "/shrines/madara/";
urls[23] = "/coding.html";
urls[24] = "/collections.html";
urls[25] = "/collections/boloties.html";
urls[26] = "/collections/civildefense.html";
urls[27] = "/collections/plushietags.html";
urls[28] = "/collections/cameras.html";
urls[29] = "/collections/newvegas.html";

if (url.contains('reading', 'tcg', 'nidai', 'tsumugi', 'madara', 'coding'));
 add ('target=_blank');
  
}

var random = Math.floor(Math.random()*urls.length);

top.location.href = urls[random];
}

function openLink() {
  // Chooses a random link:
  var i = Math.floor(Math.random() * links.length);
  // Directs the browser to the chosen target:
  parent.location = links[i];
  return false;
}

I have tried different random website link codes that people have posted to stack overflow before, but still to no effect.

How to avoid empty space in a flex flex-wrap container

I’ve created a div container, which includes a badges container and a more badge container. (See below).
The badges container has display flex flex-wrap overflow hidden and a max-height. I have a hook that checks which childs are not within the container height so I can calculate the amount of badges that are not displayed.
The container gets an empty space to the right of it and it makes a huge gap between the badges container and the more badge. I want to avoid that empty space so they will be close to each other.
How can I do it?
(I have added red background to indicate the empty space)
enter image description here

here is the example,
JSX:

 <div className="main-container">
  <div ref={containerRef} className="badge-container">
    {badges.map((badge) => (
      <div className="badge" key={badge.value}>
        {badge.label}
      </div>
    ))}
  </div>
  {Boolean(hiddenItemsCount) && (
    <div className="badge more">+{hiddenItemsCount} more</div>
  )}
</div>

CSS:

.main-container {
 display: flex;
 width: 100%;
 background-color: red;

& > .badge-container {
  display: flex;
  flex-wrap: wrap;
  overflow: hidden;
  gap: 8px;
  max-height: 34px;
}
}

.badge {
  height: 20px;
  border-radius: 5px;
  background-color: gray;
  padding: 7px 5px;

  &.more {
    white-space: nowrap;
    background-color: blue;
  }
}