How to display in the console the position with the value of the largest String within an Array

I already know that the largest string within the array has 12 letters, how do I display the value of this String, which in this case is “rioDeJaneiro”?

var cidades = ["Sãopaulo", "Riodejaneiro", "Fortaleza"]

var biggerWord = 0
for (var i = 0; i < cidades.length; i++) {
  console.log(cidades[i].length)

  if (cidades[i].length > biggerWord) {
    biggerWord = cidades[i].length 
  }
}

console.log("--------------------------------------------------")
console.log("A maior palavra tem: " + biggerWord)

I already looked for methods in the documentation but I couldn’t find them.

var cidades = ["Sãopaulo", "Riodejaneiro", "Fortaleza"]

var biggerWord = 0
for (var i = 0; i < cidades.length; i++) {
  console.log(cidades[i].length)

  if (cidades[i].length > biggerWord) {
    biggerWord = cidades[i].length
  }


}

console.log("--------------------------------------------------")
console.log("A maior palavra tem: " + biggerWord)

I am not able to get a stable orbit in this three js and cannon js simulation

I am trying to create an app which simulates celestial bodies in space.
I am using three.js for rendering and cannon.js for physics simulation. Here with this code I am not able to get a stable orbit no matter how I tweak the parameters, the planet is just eventually crashing into the central body.

const G = 1;

objectsRef.current.forEach((obj, i) => {
  if (obj.body) {
    objectsRef.current.forEach((otherObj, j) => {
      if (i !== j && otherObj.body) {
        const distanceVector = new THREE.Vector3().subVectors(
          new THREE.Vector3(
            otherObj.body.position.x,
            otherObj.body.position.y,
            otherObj.body.position.z
          ),
          new THREE.Vector3(
            obj.body.position.x,
            obj.body.position.y,
            obj.body.position.z
          )
        );
        const distance = distanceVector.length();

        if (distance > 0) {
          // Calculate the gravitational force magnitude
          const forceMagnitude = (G * obj.body.mass * otherObj.body.mass) / (distance * distance);
          const force = distanceVector.normalize().multiplyScalar(forceMagnitude);

          // Apply the force to the object
          obj.body.applyForce(new CANNON.Vec3(force.x, force.y, force.z), obj.body.position);

        }
      }
    }
  );

  // Update mesh position and quaternion based on body position and rotation
  obj.mesh.position.copy(obj.body.position);
  obj.mesh.quaternion.copy(obj.body.quaternion);
}

timestep is set to 1/60.
Am I doing something wrong?

I tried simulation using these parameters,

G = 1;

for central body:
Mass = 1000
position = (0,0,0)
Initial velocity = (0,0,0) (stationary)

for the planet:
Mass = 1
position = (20, 0, 0)
Initial velocity = (0, 7, 0)

timestep = 1/60;

It should give planet a stable orbit around the central body but the planet is eventually crashing into the central body after a few elliptical orbits.

Dataset scaling in a Chart.js bar chart for better comparison

I’m using Chart.js to graph two datasets on the same bar chart for a time-based comparison (x-axis). However, I’m encountering an issue where the height of one graph squashes or expands to fit the height of the other, making it difficult to compare them effectively.

For example, the purple graph below increases by 26x, while the blue graph increases by only 5x. Due to the scaling, it’s hard to assess the impact of these changes, as the purple graph is squashed into the height of the blue graph.

I think starting the purple graph at the same level as the blue graph at the first data point might help, but I’m concerned that the data will still be squashed to fit the blue graph’s height.

Are there specific Chart.js settings or configurations I can adjust to improve the comparability of these datasets?

My code for chart scales is as follows:

y: {
    beginAtZero: true,
    grid:  {
        display: false,
        drawBorder: false,
        drawOnChartArea: false,
     },
     ticks: {
        display: true,
     },
   },
},
y1: {
     beginAtZero: true,
     position: 'right',
     grid: {
        display: false,
        drawBorder: false,
        drawOnChartArea: false,
     },
     ticks: {
        display: true,
     },
   },
}

Multi dataset bar chart

How to open PWA by clicking on a link in a mobile browser

I have a request to click on a link on my mobile browser. If the link is already installed as PWA on my phone, I will directly open PWA on my phone. Otherwise, I will open a new browser tab
So this involves how to detect whether a PWA has been successfully installed
Seeking guidance

I tried using ‘enable user link purchasing pwa‘, but it was still an experimental feature and the effect was not good. Moreover, this feature only exists in web browsers

How to design a webpage so as not to trigger Firefox blocking the scripts?

Loading failed for the <script> with source "...".

I’m sure many Firefox users have seen this. And I’ve read solutions posted for how to get the page to render by changing one’s end-user settings in Firefox itself.

But what about web developers? How are we supposed to design pages that don’t trigger this problem? I haven’t seen recommendations for how to design around this. And I don’t want to exclude Firefox users from being able to view the site. Can anyone advise?

And I want to reiterate before someone gets trigger-happy with “Mark as Duplicate”: I’d like to fix this on the site itself, not slap a bandaid on by changing browser settings.

Problems to create a carousel of cards and work with overflow css prop

I have a carousel of cards.


.carousel {
    display: flex;
    overflow: visible;
    position: relative;
    justify-content: flex-start;
    width: 100%;
    border-radius: 15px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.cards {
    display: flex;
    transition: transform 0.5s ease-in-out;
    justify-content: space-between; /* Ensure cards are spaced */
    width: 100%; /* Use full width for the cards */
}

.card {
    flex: 0 0 30%; /* Ensure the cards have consistent size */
    margin-right: 20px;
    box-sizing: border-box;
    overflow: hidden; /* Prevent overflow */
}

.card {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
    margin: 0;
    flex: 0 0 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    transition: transform 0.3s, box-shadow 0.3s;
    text-decoration: none;
    min-width: calc(100% / 5);
    margin-right: 20px;
}

.card:hover {
    transform: scale(1.05);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
}

.card:active {
    transform: scale(0.95);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.card img {
    width: 100%;
    height: 80%;
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
    object-fit: cover;
    max-height: 400px;
}

.card .title {
    font-size: 20px;
    padding: 10px;
    font-weight: 700;
    color: #333;
    text-align: center;
}

.card .subtitle {
    font-size: 16px;
    padding: 0 10px 10px;
    text-align: center;
    color: #666;
}

.carousel-controls {
    position: absolute; /* Define os controles como posicionamento absoluto */
    top: 50%; /* Centraliza verticalmente os controles */
    transform: translateY(-50%); /* Ajusta para garantir que o centro esteja alinhado */
    width: 100%; /* Define que os controles ocupam a largura total do carrossel */
    display: flex;
    justify-content: space-between; /* Espaça os botões para as extremidades */
}

.carousel-button {
    background: #0077B6;
    border: none;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    cursor: pointer;
    transition: background 0.3s;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute; /* Posiciona os botões dentro do contêiner relativo */
    top: 50%; /* Centraliza verticalmente no contêiner */
    transform: translateY(-50%); /* Ajusta para alinhar exatamente no centro */
}

#prev {
    left: -20px; /* Ajuste à esquerda fora do carrossel */
}

#next {
    right: -20px; /* Ajuste à direita fora do carrossel */
}

   <div data-aos="fade-right" class="carousel-outer-wrapper">
                        <div data-aos="fade-right" class="carousel">
                            <div data-aos="fade-down"class="cards" id="carousel-cards">
                                <a href="de-cara-nova.html" class="card">
                                    <img src="./images/uiux.jpg" alt="Solução 1">
                                    <div class="title">UI/UX. Ganhe uma cara nova!</div>
                                    <div class="subtitle">
                                        <p data-aos="fade-left">Na O.F. Consulting, acreditamos que a experiência do usuário (UX) e o design da interface do usuário (UI) são essenciais para o sucesso de qualquer aplicação. Nossos especialistas em UI/UX desenvolvem soluções intuitivas e eficientes, sempre priorizando a usabilidade e a satisfação do cliente. A nossa abordagem começa com uma compreensão profunda das necessidades do usuário final, permitindo a criação de interfaces que sejam não apenas atraentes visualmente, mas que também facilitem a navegação e maximizem o engajamento. Trabalhamos em estreita colaboração com nossos clientes para garantir que cada detalhe da interface reflita os valores da marca e proporcione uma experiência única e eficiente.</p>
                                    </div>
                                </a>
                                <a href="web-mobile.html" class="card">
                                    <img src="./images/webdesktop_wallpaper.png" alt="Solução 2">
                                    <div class="title">Aplicativos Web e Mobile</div>
                                    <div class="subtitle">
                                        <p>Na era digital, a presença online é essencial para qualquer negócio. Nossa equipe de desenvolvimento de aplicativos web e móveis cria soluções robustas e personalizadas, que atendem às necessidades específicas de cada cliente. Seja um aplicativo responsivo ou uma solução móvel nativa, oferecemos uma experiência otimizada para qualquer plataforma. Utilizando as mais recentes tecnologias e metodologias ágeis, desenvolvemos desde aplicações simples até plataformas complexas, garantindo desempenho, segurança e escalabilidade. A O.F. Consulting está preparada para transformar suas ideias em soluções funcionais, entregando produtos que geram valor imediato ao negócio.</p>
                                    </div>
                                </a>
                                <a href="infra-cloud.html" class="card">
                                    <img src="./images/cloud-arch.png" alt="Solução 3">
                                    <div class="title">Infraestrutura e Ambientes Cloud</div>
                                    <div class="subtitle">
                                        <p>A infraestrutura tecnológica e a migração para ambientes em nuvem são essenciais para a modernização e o crescimento escalável das empresas. Na O.F. Consulting, oferecemos uma abordagem estratégica para infraestrutura e cloud, garantindo alta disponibilidade, segurança e eficiência em ambientes flexíveis e escaláveis. Implementamos soluções que reduzem custos operacionais, aumentam a produtividade e asseguram o desempenho ideal dos sistemas. Nossos especialistas em cloud computing estão prontos para planejar, implementar e gerenciar ambientes em nuvem que permitem às empresas se adaptar rapidamente às mudanças do mercado e às demandas crescentes.</p>
                                    </div>
                                </a>
                                <a href="solucoes-arquitetura.html" class="card">
                                    <img src="./images/arch.png" alt="Solução 4">
                                    <div class="title">Arquitetura de Soluções</div>
                                    <div class="subtitle">
                                        <p>Desenvolver uma solução eficaz requer uma arquitetura sólida. A O.F. Consulting se especializa em projetar e implementar arquiteturas de soluções que garantem flexibilidade, escalabilidade e segurança. Trabalhamos lado a lado com nossos clientes para entender seus desafios e identificar a melhor estrutura tecnológica para atender às suas necessidades. Nossos arquitetos de soluções utilizam padrões modernos de arquitetura, como microsserviços e arquitetura orientada a eventos, para criar sistemas robustos e fáceis de manter, alinhando as necessidades de curto prazo com a estratégia de longo prazo do cliente.</p>
                                    </div>
                                </a>
                                <a href="consultoria.html" class="card">
                                    <img src="./images/consulting_wallpaper.png" alt="Solução 5">
                                    <div class="title">Consultoria para Impulsionar seu Negócio</div>
                                    <div class="subtitle">
                                        <p>Na O.F. Consulting, nossa missão é apoiar o crescimento de nossos clientes por meio de uma consultoria estratégica e focada em resultados. Oferecemos insights valiosos que ajudam empresas a superar desafios e aproveitar oportunidades em um mercado dinâmico. Com uma abordagem personalizada, trabalhamos de forma colaborativa para entender seus objetivos de negócios e recomendar soluções que aumentam a eficiência, reduzem custos e melhoram a competitividade. Seja no planejamento estratégico, na transformação digital ou na otimização de processos, nossa consultoria está preparada para impulsionar o seu negócio a novos patamares.</p>
                                    </div>
                                </a>
                            </div>
                        </div>

                        <button class="carousel-button" id="prev">
                            <span class="material-icons">arrow_back</span>
                        </button>
                        <button class="carousel-button" id="next">
                            <span class="material-icons">arrow_forward</span>
                        </button>
                    </div>

Carousel has next and prev buttons to navigate between cards. Carousel overflow is visible, because i wanna to be able to see unfocused cards

Like this!

But when overflow is set to visible, buttons next and prev stops to work. At responsive mode (mobile) the buttons worked because overflow changes to hidden.

@media (max-width: 768px) {
    .carousel {
        width: 100vw;
        padding: 0;
        overflow: hidden;
        position: relative;
    }

JS:

function updateCarousel(direction) {
    const cardWidth = cardsContainer.children[0].offsetWidth; // Largura do card
    const scrollMargin = parseInt(getComputedStyle(cardsContainer.children[0]).marginRight) || 0;
    const scrollWidth = cardWidth + scrollMargin; // Largura total do card com margens

    const scrollStep = direction === 'next' ? scrollWidth : -scrollWidth;

    // Use scrollBy instead of manipulating scrollLeft directly to preserve overflow visible behavior
    cardsContainer.scrollBy({
        left: scrollStep,
        behavior: 'smooth'
    });
}


// Adiciona eventos aos botões de navegação
nextButton.addEventListener('click', () => {
    console.log('nextClick');
    updateCarousel('next');
});

prevButton.addEventListener('click', () => {
    console.log('prevClick');
    updateCarousel('prev');
});

// Intervalo automático para troca de cards
setInterval(() => {
    if (currentIndex < totalCards - 1) {
        currentIndex++;
    } else {
        currentIndex = 0; // Volta para o primeiro
    }
    updateCarousel();
}, 10000);

How to solve this problem?

How can I deploy my whatsapp bot on Render

I am using whatsapp-web.js to create auto reply bot for my whatsapp when I am in away mode.

If I run d app locally on my PC, it works fine but when I host it on Render as a web service, it does not work.

This is my startApp function

const startApp = async () => {
    if (!process.env.MONGODB_URI) {
        console.error("Error: MONGODB_URI environment variable is not set.");
        process.exit(1);
    }
    try {
        await mongoose.connect(process.env.MONGODB_URI);
        console.log("Connected to MongoDB");
        await client.initialize();
        console.log("WhatsApp Client initialized");
    } catch (error) {
        console.error("Error starting the app:", error);
        process.exit(1);
    }
};

startApp();

I see the following errors/warnings in render console

Docs on specifying a port: https://render.com/docs/web-services#port-binding

Port scan timeout reached, no open ports detected on 0.0.0.0. Detected open ports on localhost — did you mean to bind one of these to 0.0.0.0?

Docs on specifying a port: https://render.com/docs/web-services#port-binding

No open ports detected on 0.0.0.0, continuing to scan…

Common ways to troubleshoot your deploy: https://docs.render.com/troubleshooting-deploys

Timed out: Port scan timeout reached, no open ports detected on 0.0.0.0. Detected open ports on localhost — did you mean to bind one of these to 0.0.0.0?

I dont know how to specify port for the app, I am not using express js.

I tried to host it on render and I expected the auto reply to work

Why does setInterval in my React typewriter effect skip the second character (index 1) and display remaining characters correctly?

I am implementing a typewriter effect in my React app where I fetch a string from a URL and display it one character at a time. I expect the effect to start from the first character (index 0) and proceed through all the characters sequentially. However, the second character (index 1) is skipped, and the rest of the characters are displayed correctly.

Current behaviour:
enter image description here

Expected behaviour:enter image description here

Additional Information:
The text state is updated correctly after fetching the data.
I’ve added a 500ms delay between the display of each character.

Any suggestions on improving the logic or debugging this issue would be appreciated!

import "./styles.css";
import React, { useEffect, useState } from "react";

export default function App() {
  const [text, setText] = useState(""); // To hold the fetched text
  const [displayText, setDisplayText] = useState(""); // For the typewriter effect
  const [loading, setLoading] = useState(true); // Loading state

  // Fetching text from the URL
  useEffect(() => {
    const fetchText = async () => {
      try {
        const response = await fetch("https://example-url.com/text"); // Fetch from URL
        const data = await response.text();
        setText(data); // Save the text in the state
        setLoading(false); // Loading done
      } catch (error) {
        console.error("Error fetching the text:", error);
        setLoading(false);
      }
    };

    fetchText();
  }, []);

  // Typewriter effect logic

  useEffect(() => {
    if (!loading && text) {
      let index = 0;
      const interval = setInterval(() => {
        setDisplayText((prevText) => prevText + text[index]);
        index++;
        if (index === text.length) {
          clearInterval(interval); // Stop when all characters are shown
        }
      }, 500); // 500ms delay between characters

      return () => clearInterval(interval); // Cleanup
    }
  }, [text, loading]);

  // Rendering the text with a typewriter effect
  return (
    <div className="App">
      {loading ? (
        <p>Loading...</p> // Loading text
      ) : (
        <ul>
          {displayText.split("").map((char, index) => (
            <li key={index}>{char}</li> // Render each character in a list
          ))}
        </ul>
      )}
    </div>
  );
}

I used setInterval in useEffect to append characters one by one from the fetched string. I expected the typewriter effect to start from the first character (index 0), but it skips the second one and displays rest correctly.

outlook office adins are not able to read email during reply

I need to read the email when I am in the reply (compose) mode in outlook adins using javascript so that I can analyze the email that I am replying to and populate the reply based on the content of email.

I have added a taskpane button that triggers a javascript function with tries to populate it as prescribed above. However, as far as I have found, in draft mode, there is no way I can read the email that I am replying to. So, I have tried the following way:

  1. save the draft message to get an id
  2. use that id to get the conversation from graph api
  3. use the conversation response to populate reply

However, I am stuck on the step 2. As the message that I am saving, aren’t being retrieve from graph api. Instead it shows, 401. Here is my code:

 function handleReply(){
  // Save the draft and then call populateReply
  Office.context.mailbox.item.saveAsync(function(result) {
    if (result.status === Office.AsyncResultStatus.Succeeded) {
        let itemId = result.value; // This is the valid itemId after saving
        pops(itemId);     // Call the function to populate the reply using this itemId
    } else {
        console.error("Error saving item: " + result.error.message);
    }
  });
}

function pops(itemId) {
  console.log(itemId)
  // Get the access token and fetch the conversation thread manually
    Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function (result) {
      if (result.status === Office.AsyncResultStatus.Succeeded) {
          let accessToken = result.value;
          // let itemId = Office.context.mailbox.item.itemId;

          // Build the API URL to get the conversation thread
          let getMessageUrl = 'https://graph.microsoft.com/v1.0/me/messages/' + itemId;

          // Use fetch to get the message thread
          fetch(getMessageUrl, {
              method: 'GET',
              headers: {
                  'Authorization': 'Bearer ' + accessToken,
                  'Accept': 'application/json'
              }
          })
          .then(response => response.json())
          .then(data => {
              // Process the conversation thread from the API response
              let conversationBody = data.body.content; // HTML or plain text depending on response format
              prepopulateReply(conversationBody); // Use the thread in your reply
          })
          .catch(error => {
              console.error("Error fetching conversation thread: " + error);
              prepopulateDefaultReply(); // Use a default reply if thread is missing
          });
      } else {
          console.error("Error retrieving access token: " + result.error.message);
      }
  });
}

I am getting the itemId which is a hash value and on subsequent call to fetch the message fetch(getMessageUrl it throws 401 even though I am using same mechanism to retrieve token and token is attached in the header as it should be.

Can anyone help on finding the cause of it? Thanks for any kind of help.

Problem with POST method ([FromBody] dynamic …) on dotNet 8.0 API Server

I’ve decided to convert my React + dotNet 3.1 API app to a dotNet 8.0 one. The old one is working fine, but I want to move to a Kube Container and 3.1 is no longer supported by MS. Nothing outstanding, a rather straightforward app. On the second day I ran into this completely unexpected problem with the POST method with dynamic args passed. Dynamic is rather a point of contention for me. It simplifies things tremendously and, honestly, I did not try to see if the explicit args would work. Why, because it works in dotNet 3.1!

Here’s how to replicate it:

Tool:
Microsoft Visual Studio Professional 2022
Version 17.10.5
VisualStudio.17.Release/17.10.5+35122.118
Microsoft .NET Framework
Version 4.8.09032

Create a new project: React and ASP.NET Core; A full stack application with React project and a backend ASP.NET Core. .NET8.0 (Long Term Support)

  1. Start it. You should see windows for the Demo and Swagger.

  2. Open up the file …reactapp1.clientsrcApp.jsx . Scroll down to the function “async function populateWeatherData()”, add another function and save the file. Port is the one you see in your demo page:

    async function populateWeatherData_2() {
        const myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/json");
    
        const raw = JSON.stringify({
            id: 0,
            name: "string",
            isComplete: true,
        });
    
        const requestOptions = {
            method: "POST",
            headers: myHeaders,
            body: raw,
            redirect: "follow",
        };
    
        try {
            const response = await fetch(
                "http://localhost:5173/WeatherForecast/PostWeatherForecast",
                requestOptions
            );
            const result = await response.text();
            console.log(result);
        } catch (error) {
            console.error(error);
        }
    }
    
  3. Open up the file …ReactApp1.ServerControllersWeatherForecastController.cs. Add the below function and save the file.

    [HttpPost(Name = "PostWeatherForecast")]
    public IEnumerable<WeatherForecast> Post([FromHeader] dynamic args)
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
    
  4. Restart the project to see POST added in the Swagger:

    enter image description here

  5. Put a break point on the line just below the method name in source file. Execute “Try it out” and verify that the break point worked and you can see the value of args.

  6. Go back to the App.jsx and put a break point inside the function.

  7. Refresh the demo page. Verify that the above break point works:

  8. Press F5 to continue and verify that it works in “public IEnumerable<WeatherForecast> Get()” as well:
    enter image description here

    At this point we can see that all works as expected.

  9. Go back to App.jsx and change the App function to point to the post request.
    enter image description here

  10. Put a break point in “populateWeatherData_2” function and another one in the catch section. Save the file. Either right after save or after refresh verify that execution stopped at the break point:

  11. Continue (F5)[may require a couple of F5s] to see that it went directly to the error, and did not get the server method!
    enter image description here

  12. This is the complete Controller definition:

    using Microsoft.AspNetCore.Mvc;
    namespace ReactApp1.Server.Controllers
    {
        [ApiController]
        [Route("[controller]")]
        public class WeatherForecastController : ControllerBase
        {
            private static readonly string[] Summaries = new[]
            {
                "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
            };
    
            private readonly ILogger<WeatherForecastController> _logger;
    
            public WeatherForecastController(ILogger<WeatherForecastController> logger)
            {
                _logger = logger;
            }
    
            [HttpGet(Name = "GetWeatherForecast")]
            public IEnumerable<WeatherForecast> Get()
            {
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                })
                .ToArray();
            }
    
            [HttpPost(Name = "PostWeatherForecast")]
            public IEnumerable<WeatherForecast> Post([FromHeader] dynamic args)
            {
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                })
                .ToArray();
            }
    
        }
    }
    
    

The server responds correctly to POST when the Postman is used. The Postman was useful for the POST function creation, but I do not trust it any more, because it looks like it uses CURL.

I used both ‘fetch’ and ‘Axios’ and tested the code with VSC – same result. If you try to dig debug deeper you can see that the request reaches the API and breaks in one of the methods. I am not sure if it is MS bug or I am missing something.

Did anybody ran into this? Any suggestions?

Mouseover event doesn’t propagate as expected (Add Button effect)

I wanted to do a simple highlight on a button at the place where you hover over it, following the cursor.
If anyone knows a way to do this without js that would be even better (found one crazy post out there), but i tried to do it with a eventhandler for mouseover.

I am moving the nested div when hovering over the button, but on my site it doesn’t propagate the event when hovering over the child and in this simple recreation it only works when hovering over the child.
Feeling like i am doing something really wrong here but can’t see it.

var button = document.querySelector('.button');
var highlightDiv = document.querySelector('.highlight');

button.addEventListener('mouseover', (e) => {
    const x = (e.pageX - button.offsetLeft - 300 / 2) + 15;
    const y = (e.pageY - button.offsetTop - 100 / 2) + 15;
    highlightDiv.style.setProperty('--x', `${x}px`);
    highlightDiv.style.setProperty('--y', `${y}px`);
});
.button {
  border: 1px solid black;
  width: 400px;
  height: 70px;
}

.highlight {
  height: 40px;
  width: 40px;
  background: radial-gradient(#e66465, #9198e5);
  transform: translate(var(--x), var(--y));
}
<button class="button">
  Button Text
  <div class="highlight"></div>  
</button>

Creating a sidebar that follows and reaches out to mouse

I recently saw this [sidebar][1] that follows the mouse and “reaches out” to the mouse when it gets close enough and I was wondering if anyone had any tips on how to implement it? I saw this [post][2] with the answer to have a menu that follows the mouse, but I’m unsure of where to go next from here. I really like how the example has the menu sort of “grow” to where the mouse is and have it come out of the rectangular sidebar.

[1]: https://codemyui.com/gooey-sidebar-stretch-menu-concept/

[2]: Sidebar hide/show button that follows cursor mouse?

<div class="A"></div>
.A {
    top:0px;
    position:absolute;
    width:50px;
    height:50px;
    border-radius: 50;
    border:1px solid blue;
}
var posY;

$(document).mousemove( function(e) { 
   posY = e.pageY;
    $('.A').css({'top': posY});
});

Same useAsyncData vs useFetch but useAsyncData doesn’t fetch on the first load or hard refresh. Why?

I have those two functions and I think they are the same? But for some reason the useLazyAsyncData doesn’t seem to make the api call on initial load – it will if I navigate away and navigate back. Any thoughts on what I am doing wrong?

const {
  status,
  data: airlines,
  error,
  refresh
} = useFetch('/api/airlines/list', {
  lazy: true,
  params: queryItems,
  transform: (airlines: ListResult<Airline>) => transformer(airlines)
})

const {
  status,
  data: airlines,
  error,
  refresh
} = await useLazyAsyncData(
  'airlines',
  () =>
    $fetch('/api/airlines/list', {
      params: queryItems
    }),
  {
    transform: (airlines: ListResult<Airline>) => transformer(airlines)
  }
)

Browser push notification received but never triggers

Using webpush, just a quick and dirty POC to see if i can get push notifications to work. index.html just has two buttons, one to subscribe, one to test the push notification.

I have sufficient logs to see that the subscription happens. Clicking notify does post to /notify and returns a 200. I generated keys (pair is in server.js, the public key is in index.html)

Chrome outputs the worker’s console.log‘s, but neither Chrome nor Firefox actually fire the push notification.

Running this locally on port 3000 (node server.js) and then I have an A record pointing to a subdomain I have a reverse proxy (nginx proxy manager) running to force SSL (with websockets enabled if that matters). So I’m accessing this from a valid certificate https://sub.mydomain.com in Chrome and Firefox, but the push notification never actually fires.

I’m certain push notifications are allowed in browser settings, the subscription works to enable the permission for the domain. I even tried enabling service worker debugging in Firefox–no dice.

server.js

const express = require('express');
const webpush = require('web-push');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

const publicVapidKey = 'my pub key';
const privateVapidKey = 'my priv key';

webpush.setVapidDetails('mailto:[email protected]', publicVapidKey, privateVapidKey);

let subscriptions = [];

app.post('/subscribe', (req, res) => {
    const subscription = req.body;
    subscriptions.push(subscription);
    console.log('subscriptions: ', subscriptions);
    res.status(201).json({});
});

app.post('/notify', (req, res) => {
    console.log('hit /notify');

    const payload = JSON.stringify({
        title: 'New Notification',
        message: 'You have a new notification!'
    });

    subscriptions.forEach(sub => {
        webpush.sendNotification(sub, payload).catch(err => {
            console.error('Error sending notification:', err);
        });
    });
    res.status(200).json({});
});

app.use(express.static('public'));

app.listen(3000, () => {
    console.log('Server started on port 3000');
});

worker.js

self.addEventListener('push', event => {
    console.log('push received');
    console.log(event);
    console.log(event.data);
    console.log(event.data.json());
    const data = event.data.json();
    // debugger;
    self.registration.showNotification(data.title, {
        body: data.message,
        icon: '/icon.png'
    });
    // tried this too:
    //const notification = new Notification(data.title, {
    //    body: data.message,
    //    icon: '/icon.png'
    //});
});

index.html (relevant parts)

// Subscribe for push notifications
        async function subscribeUser() {
            const registration = await navigator.serviceWorker.register('/worker.js', { scope: '/' });
            const subscription = await registration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
            });
            await fetch('/subscribe', {
                method: 'POST',
                body: JSON.stringify(subscription),
                headers: { 'Content-Type': 'application/json' }
            });
            alert('Subscribed successfully!');
        }

        // Send a test notification
        async function sendNotification() {
            await fetch('/notify', { method: 'POST' });
        }

        function urlBase64ToUint8Array(base64String) {
            const padding = '='.repeat((4 - base64String.length % 4) % 4);
            const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
            const rawData = window.atob(base64);
            return Uint8Array.from([...rawData].map((char) => char.charCodeAt(0)));
        }

        document.getElementById('subscribe').addEventListener('click', subscribeUser);
        document.getElementById('notify').addEventListener('click', sendNotification);

How to Use Firebase Authentication with JS File?

createUserWithEmailAndPassword is not defined

How can I access the auth object initialized in index.html within my auth.js file? Should I pass it as an argument, or is there a better way to manage the Firebase authentication in a modular JavaScript setup? Any guidance would be greatly appreciated!



<form id="signup-form">
    <div class="input-field">
        <input type="email" id="signup-email" required />
        <label for="signup-email">Email address</label>
    </div>
    <div class="input-field">
        <input type="password" id="signup-password" required />
        <label for="signup-password">Password</label>
    </div>
    <button type="submit">Sign Up</button>
</form>

<script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-app.js";
    import { getAuth } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-auth.js";

    const firebaseConfig = {
        apiKey: "API_KEY",
        authDomain: "AUTH_DOMAIN",
        projectId: "PROJECT_ID",
        storageBucket: "STORAGE_BUCKET",
        messagingSenderId: "MESSAGING_SENDER_ID",
        appId: "APP_ID",
        measurementId: "MEASUREMENT_ID"
    };

    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);  // Initializes the auth service
</script>
<script src="scripts/auth.js"></script>

```html


```js

const signupForm = document.querySelector('#signup-form');

signupForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const email = signupForm['signup-email'].value;
    const password = signupForm['signup-password'].value;

    createUserWithEmailAndPassword(auth, email, password).then((cred) => {
        console.log(cred);
    }).catch((error) => {
        console.error("Error creating user:", error);
    });
});

```js