Adding Tailwind hover class using classList.add in Javascript

clockBtn.classList.add(..., "opacity-0", "hover:opacity-100");

The clockBtn button is dynamically created in a function defined in .js file.

I am trying to use hover:opacity-100 so that the button, which is usually not visible, shows up upon hovering over the button.

But, the button stays invisible even when the cursor is over the button.

Is this the right way to add this hover Tailwind class in Javascript?

Should I Avoid Global Variables At All Cost?

In my project, I am trying to create a chat room. In the chat room, I need to send different kind of data about other sections of my app. I use web sockets to that.

To send same data to every client in the room they are inside of, I need to iterate over like, all of the clients. And if like, I have 1000 clients, it could create lag, so messages or other datas could be laggy. To prevent this, I can actually create a map object and set room name, to that key(room name) name I can use set object as value that is having an instance of client object of web socket itself. So thanks to that global variable map object I saved performance of iterating through all clients to just to send to the clients in the same room.

Code for the loop I am currently using to avoid global variable:

ws.communityName = communityName;

// Send to all clients in the same community
webSocket.clients.forEach((client) => {
      if(client.communityName === communityName) {
            client.send(stringifiedActiveUsers);

            // Send only to owner of the community within user's community 
            if(client.userid === communityOwnerId) {
                  client.send(suspendedUsersData);
            }
      }
});

That is my logic on how to send data to all clients in the same room. But I am using global variable, which I shouldnt because it could create memory leak problems etc…

Do you think there is a more efficient solution to this problem? Should I use global variable to save performance?

How to pass information to a GLTFLoader callback function?

With THREE.js and GLTFLoader I’m loading models. After the model is loaded I’d like to cache it in a dictionary. The only hold of the model I seem to get in the loader callback. I need to pass the key-string to the loader to save the loaded object in the dictionary.

How do I pass a string to the GLTFLoader callback?

Code:

var modelSources = { car: "resources/models/my-model.glb" };
modelSources.length = 0;
var dictionary = {};
for (var key in modelSources)
{
    var value = modelSources[key];
    if (typeof(value) === "string")
    {
        if (value.startsWith("http") || value.startsWith("resources/"))
        {
            modelSources.length++;
            var loader = new GLTFLoader();
            loader.load(value, function (group)
            {
                var obj = group.scene.children[0];
                // need key or at least value
                dictionary[key] = obj;
            });
        }
    }
}

window.visualViewport.scale is not updated until stack of function calls ends

This is part of a large Tampermonkey userscript i’m writing.
It changes window.visualViewport.scale and use the resize event to show the new value.

In the snippet it doesn’t do anything, but on the page it works (using the debug tools with the device toolbar activated)

// ==UserScript==
// @name         provaui
// @namespace    http://tampermonkey.net/
// @version      2025-09-20
// @description  try to take over the world!
// @author       You
// @match        https://www.soundcraft.com/ui24-software-demo/mixer.html
// @icon         https://www.google.com/s2/favicons?sz=64&domain=soundcraft.com
// @grant        none
// ==/UserScript==
let UserScale=1; // current scale variable
let dbgLog="";

function setViewportScale(ViewScale) {
  console.log(dbgLog+"setViewportScale Start"); dbgLog=dbgLog+"....";
  let NewScale = Number(ViewScale);
  CurrentScale=NewScale;
  console.log(dbgLog+"NewScale: "+NewScale);

  console.log(dbgLog+"Applying new scale");
  let vpElement = document.querySelector("meta[name=viewport]");
  if (!vpElement){
    vpElement=document.createElement('meta');
    vpElement.name = "viewport";
    document.getElementsByTagName('head')[0].appendChild(vpElement);
  }
  let content = 'width=device-width, initial-scale=' + NewScale + ', maximum-scale=1.5, minimum-scale=0.5, user-scalable=yes';
  vpElement.setAttribute('content', content);
  console.log(dbgLog+"VP Scale is "+ window.visualViewport.scale);
  dbgLog=dbgLog.replace("....",""); console.log(dbgLog+"setViewportScale End");
}
// =============================================================
function updateSize() {
  console.log(dbgLog+"updateSize Start"); dbgLog=dbgLog+"....";
  console.log(dbgLog+"VP Scale is "+ window.visualViewport.scale);
  dbgLog=dbgLog.replace("....",""); console.log(dbgLog+"updateSize End");
}
// =============================================================


// zoom button
let aDiv = document.createElement ('div');
aDiv.setAttribute ('id', 'ZoomButtonContainer');
aDiv.style = 'position:absolute; top: 12px; left: 10px; z-index: 99998; background-color: orange; display: flex; justify-content: center; align-items: center; padding: 5px;'
aDiv.innerHTML = ''
    + '<button id="bZoom" type="button" style="width:130px !important;">Zoom</button>'
    + '<button id="bLog" type="button" style="width:130px !important;">Log</button>'
    ;
document.body.appendChild (aDiv);
document.getElementById('bZoom').addEventListener('click', function(event) {
  event.stopPropagation();
  if (UserScale==1) {
    UserScale = 0.7;
  }else{
    UserScale = 1;
  }
  setViewportScale(UserScale);
});
document.getElementById('bLog').addEventListener('click', function(event) {
  console.log(dbgLog+"Log Button: VP Scale is "+ window.visualViewport.scale);
});

// Add an event listener for window resize
window.addEventListener('resize', updateSize);

(function() {
    'use strict';

    // Your code here...
})();

This same exact code, on the page declared in the userscript header, produces this output:

Log Button: VP Scale is 1

setViewportScale Start
....NewScale: 0.7
....Applying new scale
....VP Scale is 1
setViewportScale End
updateSize Start
....VP Scale is 1
updateSize End

Log Button: VP Scale is 0.7002456784248352

setViewportScale Start
....NewScale: 1
....Applying new scale
....VP Scale is 0.7002456784248352
setViewportScale End
updateSize Start
....VP Scale is 0.7002456784248352
updateSize End

Log Button: VP Scale is 1

As you can see, the resize event still shows the old scale value, even if the scaling works flawlessy.
What am i doing wrong? How can i read the updated scale value?

How to highlight Tamil spelling mistakes in a Chrome Extension using JavaScript?

I’m building a Tamil Spell Checker Chrome Extension. I want to highlight incorrect words in text input fields or on web pages.

I have a list of correct Tamil words in a dictionary (JavaScript array), and I want to compare each word on the page with this list.

Problem: I’m not sure how to efficiently check each word and highlight only the wrong ones in real-time without slowing down the page.

I looped through each word and checked against my dictionary.

Used innerHTML to wrap wrong words in tags with red color.

Issue: This sometimes breaks the page formatting and is slow on large paragraphs.

React Native / NativeWind text-white not applying on specific element

I’m building a React Native app with Expo Router and NativeWind. Most of my Tailwind classes work fine, but for some reason, the text-white class does not apply on one particular element, while other texts with text-white work correctly.

import '../../global.css'
import {Text, View, Image, ScrollView, ActivityIndicator} from "react-native";
import {images} from "@/constants/images";
import {icons} from "@/constants/icons";
import SearchBar from "@/components/SearchBar";
import { useRouter } from "expo-router";
import useFetch from "@/services/useFetch";
import {fetchMovies} from "@/services/api";

export default function Index() {
    const router = useRouter();

    const { data: movies,
            loading: moviesLoading,
            error: moviesError } = useFetch(() => fetchMovies({ query: '' }))

  return (
      <View className="flex-1 bg-primary">
          <Image source={images.bg} className={"absolute w-full z-0"}></Image>

          <ScrollView className="flex-1 px-5" showsVerticalScrollIndicator={false} contentContainerStyle={{minHeight: "100%", paddingBottom: 10}}>
              <Image source={icons.logo} className="w-12 h-10 mt-20 mb-5 mx-auto"/>

              {moviesLoading ? (
                  <ActivityIndicator
                      size="large"
                      color="#0000ff"
                      className="mt-10 self-center"
                  />
              ) : moviesError ? (
                  <Text>Error: {moviesError?.message}</Text>
              ) : (
                  <View className="flex-1 mt-5">
                      <SearchBar
                          onPress={() => router.push("/search")}
                          placeholder="Search for a movie"
                      />

                      <>
                          <Text className="text-lg font-bold mt-5 mb-3 text-white">Latest Movies</Text>
                      </>
                  </View>
              )}
          </ScrollView>
      </View>
  );
}

The line in subject is;

<Text className="text-lg font-bold mt-5 mb-3 text-white">Latest Movies</Text>

I couldn’t figure out why it is not working.

JAVASCRIPT fetching of HTML li text content [closed]

I am working on an api project, and I need to gather the contents of the li using my javascript. There can be multiple of these li‘s

My html (just a small section)

<div>
    <button id="roomListButton">Click me to see what rooms your in</button>
        <ul id="roomsList">

        </ul>
            
</div>

My javascript (not everything)

const roomsListR = document.querySelector('#roomsList');

const delRoomButTEMPLATE = document.createElement('button')
delRoomButTEMPLATE.classList.add('deleteRoomBtn');
delRoomButTEMPLATE.innerHTML = `Leave this room`;


      const fetchRoomsAndProcess = async (event) => {
            console.log('fetching rooms')
            event.preventDefault();

            const response = await fetch('/getRooms');
            const jsonResponse = await response.json();
            const result = jsonResponse.result

            // Preparatory clean of the rooms list
                roomsListR.innerHTML = ``
            
            for (let i = 5; i != 0; i--) {
                let currentRoom = result.splice(0, 1)
                let currentRoom2 = currentRoom[0]
                let currentRoom3 = currentRoom2['roomname']
                console.log('currentRoom3 : ', currentRoom3);

                // Now do the stuff with currentRoom
                const li = document.createElement('li');
                li.innerHTML = `${currentRoom3} ${delRoomButTEMPLATE.outerHTML}`

                li.addEventListener('click', (event) => {
                    console.log('button clicked.')
                    const parent = event.target.parentNode
                    console.log(parent.innerHTML)
                })

                roomsListR.appendChild(li)

                if (result.length == 0) {
                    break
                }
            }

        }

The syntax: li.textContent does not work as it returns the text content of the button element inside it as well. li.innerText for some reason does the same thing. And li.innerHTML includes the tag which is not what I want.

Is there a shortcut for retrieving just the text in the node, not including any tags or anything inside of those tags?

Redirection problem in NextJs notfound-page not working

i am new to nextjs and i am trying to build a small website. I am trying to make it multilingual with /it and /el so right now i have a locale folder with all my nested folders and pages. my main page.tsx is now in locale folder so the domain/ redirects me to domain/el as el is the default. but the main issue is that the only route in root is “domain”/Admin and nothing else and here is the problem: if i write “domain”/ssadsdha which means something random word the app gets me to domain/random but it shows me the homepage and not the not-found.tsx i tried using a custom notfound page and the default but still. the weird thing is that the notfound.tsx works if i write domain/random/random etc.. but not in domain/kfndk , I even tried adding a root page.tsx to redirect all users to the /el domain but still doesnt work

JAVASCRIPT fetching of HTML li text content

I am working on an api project, and I need to gather the contents of the li using my javascript. There can be multiple of these li‘s

My html (just a small section)

<div>
    <button id="roomListButton">Click me to see what rooms your in</button>
        <ul id="roomsList">

        </ul>
            
</div>

My javascript (not everything)

const roomsListR = document.querySelector('#roomsList');

const delRoomButTEMPLATE = document.createElement('button')
delRoomButTEMPLATE.classList.add('deleteRoomBtn');
delRoomButTEMPLATE.innerHTML = `Leave this room`;


      const fetchRoomsAndProcess = async (event) => {
            console.log('fetching rooms')
            event.preventDefault();

            const response = await fetch('/getRooms');
            const jsonResponse = await response.json();
            const result = jsonResponse.result

            // Preparatory clean of the rooms list
                roomsListR.innerHTML = ``
            
            for (let i = 5; i != 0; i--) {
                let currentRoom = result.splice(0, 1)
                let currentRoom2 = currentRoom[0]
                let currentRoom3 = currentRoom2['roomname']
                console.log('currentRoom3 : ', currentRoom3);

                // Now do the stuff with currentRoom
                const li = document.createElement('li');
                li.innerHTML = `${currentRoom3} ${delRoomButTEMPLATE.outerHTML}`

                li.addEventListener('click', (event) => {
                    console.log('button clicked.')
                    const parent = event.target.parentNode
                    console.log(parent.innerHTML)
                })

                roomsListR.appendChild(li)

                if (result.length == 0) {
                    break
                }
            }

        }

The syntax: li.textContent does not work as it returns the text content of the button element inside it as well. li.innerText for some reason does the same thing. And li.innerHTML includes the tag which is not what I want.

Is there a shortcut for retrieving just the text in the node, not including any tags or anything inside of those tags?

Why Symbols and BigInt can’t be instancied using “new” keyword? [duplicate]

While I was learning the language, I became interested in primitive types and their object wrappers.

While I was in my code editor discovering this language feature, I discovered that any of these object wrappers could be instantiated with the keyword “new.” I then discovered that not using it (new) transforms this “constructor” into a conversion function. Very well, the documentation tells me that this is an intentional feature of the language.

However, as I continued testing, I realized that trying to instantiate the BigInt and Symbol wrapper objects was impossible (returns a TypeError).

So, I went to read the documentation, and it clearly states that:

  • Attempting to construct it with new throws a TypeError.
  • Performs a type conversion when called as a function rather than as a constructor (like all other object wrappers).
  • Is not intended to be used with the new operator or to be subclassed.

But nothing more!

The question I’m asking myself is: Why can all other wrapper objects be instantiated with the keyword new except for BigInt and Symbol?

My hypothesis was that in the symbol example, it is a bit of a special case in the sense that it is not “intended” to be manipulated, hence the instantiation.

Sorry for this long message, I feel like the answer is obvious and, worse, right in front of my eyes.

PS: I know that I will never instantiate wrapper objects in JavaScript in a real-world situation, I’m just wondering because I’m curious about what happens under the hood.

By the way, if you have any anecdotes or websites that explain in detail how things work, I’d love to hear them.

How does using Date.now() inside useMemo prevent optimizations?

My main question is: I want to understand why adding Date.now() inside useMemo seems to break the optimization. As far as I know, a React component wrapped with React.memo only re-renders if its props change, so in this case, it should re-render only when items or onItemClick change. And when items changes, useMemo will recompute processedItems anyway because the array reference is different.

So why does it matter whether Date.now() is included or not?

Can someone please explain what I’m missing here? It seems like a simple question, but I’ve been struggling to fully understand this for days.

const ExpensiveComponent = React.memo(({ items, onItemClick }) => {
  const processedItems = useMemo(() => {
    return items.map((item) => ({
      ...item,
      processed: true,
      timestamp: Date.now(),
    }));
  }, [items]);
  return (
    <div>
      {" "}
      {processedItems.map((item) => (
        <div key={item.id} onClick={() => onItemClick(item)}>
          {item.name}
        </div>
      ))}{" "}
    </div>
  );
});

I tried logging with and without Date.now(), and the outputs appeared essentially the same, except that the timestamps are missing when it’s not included which is the expected result.

Object.entries(item) as [keyof TCreate,TCreate[keyof TCreate]][]

I understand that keyof TCreate gives a union of all keys in the type TCreate. But I’m confused about `TCreate[keyof TCreate]`. What exactly does it represent, why do we write it this way, and how does it work in TypeScript? I don’t fully get how it handles the values of the object and why it produces a union of all possible value types instead of preserving the specific type for each key

How to have two instances of jQuery .load?

I know next to nothing about JS at the minute, I use this to import images from a separate HTML file into a DIV but I don’t know how to add a second path where I can have the same thing again but from a different file into a different DIV

Copying this block of code didn’t work, but I don’t know how to add it to the same script if you get what I mean.

<script type="text/javascript">
 jQuery(document).ready(function(){
   jQuery("#taskmarquee").load("/pagebuttons.html #PageBtns");
 });
</script>

Does modern JavaScript/TypeScript have ways to conditionally “swap” code when being bundled if features are avaiable?

Do JavaScript bundlers (or TypeScript) have some kind of feature that allows to bundle the code and “swap” some lines if specific features are available, like #ifdef macros in C or C#?

I have the following function, in this form should be compatible with any modern JS engine and browser. My target is to ensure this function always work.

public dispatch(): IteratorObject<(event: T) => void, void, void> {
    const listeners = [...this.#_listeners];
    return (function *() { for (const listener of listeners) yield listener; })();
}

Since March 2025 the new Iterable.from method (and other too) have been introduced and the MDN page says is newly available with modern browsers too.

The function from before could be rewritten like so:

public dispatch(): IteratorObject<(event: T) => void, void, void> {
    return Iterator.from([...this.#_listeners]);
}

And now the rewritten function only works with the most recent update or from an engine that supports the method.

Some scripts I’ve seen fix a similar problem with a constant at the top of the script that checks if a feature is avaiable and either use one of two method that use different features. then this is used inside the script.

Does modern JavaScript bundlers or TypeScript support for a more “literal” (if that’s how to be called) way to replace lines of code depending on version or features available?

Notes:

  • The this.#_listeners is an array.

  • The showcased functions returns IteratorObject because that’s the common class between a generator and Iterator.from

In a html document, How to make sure that body is the only scrollable ancestor?

I have a document in which absolutely positioned divs get attached to the dom and removed from the dom. Sometimes, the newly attached divs are either partially visible or not visible at all. So I have to use the scrollintoview method as described here. But I need to have css setting to make sure that the scrolling happens with respect to body. So, my question is, How to make sure that body is the only scrollable ancestor?

REFERENCE: mdn web page there is reference to “scrollable ancestor”