How to place text over multiple images over a grid form

I’m trying to have my hidden description show over each imageContainer it’s connected to. However no matter which one I point to the description shows somewhere else on the page. Furthermore, I must have messed something up with the loop.Do I need an extra div somewhere? Some images have 2 descriptions that show up when you hover over them instead of 1, and some you get nothing.

document.addEventListener('DOMContentLoaded',function () {
  const images=document.querySelectorAll('.imageContainer')
  const descriptions=document.querySelectorAll('.hidden');
  images.forEach((image, index) => {
    image.addEventListener('mouseover', () => {
        descriptions[index].style.display = 'block';
    });

    image.addEventListener('mouseout', () => {
        descriptions[index].style.display = 'none';
    });
});
});
.imageContainer{
    position: relative;
    display: inline-block;
    width: 100%;
}
.imageContainer:hover ~ .hidden{
    position: absolute;
    
    transform: translate(-50%, -50%);
    z-index: auto;
    color: white;
    background: rgba(65, 64, 64, 0.51);
}
 <div class="container justify-content-evenly">
    <div class="row">
      <div class="imageContainer col-md-6">
        <img
          src="images/Mermaid.png"
          class="img-fluid"
          alt="mermaid"
          id="page1-img"
        />
      </div>
    <div class="hidden description col-md-6 mb-5">
      <div class="appTitle text-start text-decoration-underline" id="app-title">
        Mermaid Page
      </div>
      <p class="text-start p-0">
        Now this was the first webpage I ever created. It might not be
        responsive, but I find beauty in it's simplicity. It has
        significant amount of CSS, very little Javasript, and the
        information I used is linked to it's orginal source. It honestly
        made me want to learn more about coding.
      </p>
      <a
        class="btn btn-dark text-start text-start border border-white p-3"
        href="https://my-first-site-jj.netlify.app/"
        target="_blank"
        role="button"
        id="launch-app"
        title="Learn about Memaids"
        >Launch App</a
      >
    </div>
        <div class="hidden description col-md-6 mb-5">
          <div class="appTitle text-start text-decoration-underline" id="app-title">
            World Clock App
          </div>
          <p class="description  text-start p-0">
            Check what the time is not only in your area, but in the listed
            countries. I implemented moment_timezone and Javascript to give
            you the different timezone you see here. Hope you check it out and
            enjoy.
          </p>
          <br />
          <a
            class="btn btn-dark text-start text-start border border-white mb-5 p-3"
            href="https://world-clock-jordanka.netlify.app/"
            target="_blank"
            title="Check The Time"
            role="button"
            id="launch-app"
            >Launch App</a
          >
        </div>
        <div class="imageContainer col-md-6">
          <img
            src="images/clock.PNG"
            alt="clock app"
            class="img-fluid"
            id="page1-img"
          />
        </div>

          <div class="imageContainer col-md-6">
            <img
              src="images/Weather_App.png"
              alt="weather app"
              class="img-fluid"
              id="page1-img"
            />
          </div>
          <div class="hidden description col-md-6 mb-5">
            <div class="appTitle text-start text-decoration-underline" id="app-title">
              Weather App
            </div>
            <p class="description text-start p-0">
              Do you want to know your 5 day forecast? What about in any city
              in the world? Just type a city in the search engine and see the
              results. This app was made with React and to get this
              information I utilized Shecodes Weather API and my own APIkey.
            </p>
            <br />
            <a
              class="btn btn-dark text-start text-start border border-white p-3"
              href="https://jj-weather-react.netlify.app/"
              target="_blank"
              title="Check Your Weather"
              role="button"
              id="launch-app"
              >Launch App</a
            >
          </div>

          
          <div class="hidden description col-md-6 mb-5">
            <div class="appTitle text-start text-decoration-underline" id="app-title">
              Dictionary App
            </div>
            <p class="description  text-start p-0">
              Look up anyword you want, with an old-timey feel, and possiblily have some images for examples. I incorporated two different api keys for this project. I connected the pexel api to the dictionary api so the images would match the researched word. 

            </p>
            <a
              class="btn btn-dark text-start text-start border border-white p-3"
             href="https://jj-dictionary-app.netlify.app" 
              target="_blank"
              role="button"
              id="launch-app"
              title="look up words with my Dictionary"
              >Launch App</a
            >
          </div>
          <div class="imageContainer col-md-6">
            <img
              src="images/Dictionay.png"
              alt="Dictionay app"
              class="img-thumbnail"
              id="page1-img"
            />
          </div>

          <div class="imageContainer col-md-6">
            <img
              src="images/Marc-landing.png"
              alt="landing page about Marc Anthony"
              class="img-thumbnail"
              id="page1-img"
            />
          </div>
          <div class="hidden description col-md-6 mb-5">
            <div class="appTitle text-start text-decoration-underline" id="app-title">
              Marc Anthony Landing Page
            </div>
            <p class="description text-start p-0">
              Do you love Marc Anthony music as much as I do? Or do you simply want to open your ears and mind to some salsa music? Then who better to listen to than the man who's known as the king of Salsa. Click on the launch app to have a listen
            </p>
            <a
              class="btn btn-dark text-start text-start border border-white p-3"
             href="http://jj-marcanthony-project.netlify.app"
              target="_blank"
              role="button"
              id="launch-app"
              title="Learn about Marc Anthony"
              >Launch App</a
            >
          </div>
      
          <div class="hidden description col-md-6 mb-5">
            <div class="appTitle text-start text-decoration-underline" id="app-title">
              AI Italian Recipe
            </div>
            <p class="description text-start p-0">
              Ever wanted to make an Italian dish but didn't know where to start? Well take out the guess work and utilize my AI generated Italian Recipe app. Where you can simply type lasagna and it give you a delicious recipe within a minute.
            </p>
            <a
              class="btn btn-dark text-start text-start border border-white p-3"
             href="https://italian-food-generator.netlify.app" 
              target="_blank"
              role="button"
              id="launch-app"
              title="Use AI to get a new Italian recipe"
              >Launch App</a
            >
          </div>
          <div class="imageContainer col-md-6">
              <img
                src="images/AIrecipe.png"
                alt="italian recipe generator"
                class="img-thumbnail"
                id="page1-imgr"
              />
            </a>
            </div>
        </div>

Sidebar toggle not working on small screen

I have a div in an html like below:

<div id="sidebar" class="mainsidebar">

And a button on a different div on same html like this:

<button type="button" id="sidebarCollapse" class="navbar-btn">

And javascript goes like (no jQuery, all vanilla):

document.getElementById("sidebarCollapse").addEventListener('click',
    function() {
        document.getElementById("sidebar").classList.toggle("active");
        this.classList.toggle("active");
    });

Clicking sidebarCollapse button works as expected on full (large) screen. i.e. the sidebar toggles fine.

Situation: On small screen mode, the sidebar goes away expected but it never comes back by clicking sidebarCollapse button. In “inspect” mode I can clearly see the js function works. That means it toggles active class to sidebar just fine but for some reason the sidebar never appears.

What might be missing?

I have tried pretty much everything and now giving up. Any pointers will be helpful. I can provide all the info if anyone needs. For this purpose, I have put the whole thing here on github too. It has full html css and js.

How to Access Values Outside of the Scope of an Event Listener

I have an event listener tied to a button on the form to get the player’s names. I can access the player’s name inside the event listener, but have no way of pulling it out to create a new Player.

Surely, we are not supposed to write the rest of the program inside the event listener just so we can access these values right?

    let player1 = new Player();
    let player2 = new Player();

    let win;
    let whoWon;

    // Hide the play again button
    playAgain.classList.add('hidden');

    // Get the players
    subBtn.addEventListener('click', (e) => {
        e.preventDefault();

        // Generate a random token for player1
        let p1Token = generateToken();

        player1.setPlayerName(e.target.form[0].value);
        player1.setToken(p1Token);

        // Get the token for player 2
        let p2Token;
        if (player1.getToken() === 'X') {
            p2Token = 'O';
        } else {
            p2Token = 'X';
        }

        player2.setPlayerName(e.target.form[1].value);
        player2.setToken(p2Token);
    });

Here is the player module:
   class Player {
    constructor(name='p1', token='X') {
        this.name = name;
        this.token = token;
        this.wins = 0;
    }

    getPlayerName = () => this.name;
    setPlayerName = (name) => this.name = name;
    getToken = () => this.token;
    setToken = (val) => this.token = val;
    getWins = () => this.wins;
    addWin = () => ++this.wins;

}

export default Player;

How can I send values outside of the scope of the listener? I would also need to prevent the rest of the script from running until the listener has ran.

Add customer id or custom field to ClickPatrol from protection

We’re using ClickPatrol’s form protection.
To integrate it with HubSpot, we need to modify the main HubSpot JavaScript. Normally, this allows us to add custom inputs such as prefilled email addresses, user IDs, etc.

According to GetFormProtection.com, it’s possible to insert this data, but I’m not sure how to implement it. Can you advise on the correct method?

What is my main issue:
All the custom field we inject are not visible in Hubspot. The field:

customfield

is not getting visible in Hubspot.

My current hubspot code is looking like this some what:

<script>
  hbspt.forms.create({
    region: "na1",
    portalId: "123456",
    customfield: "name of the user"
    formId: "abcdef12-3456-7890-abcd-1234567890ab";
  });
</script>

The code that i get form get form protection is:

<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/embed/v2.js"></script>
<script charset="utf-8" type="text/javascript" src="https://api.getformprotection.com/?skid=[[user_id]]"></script>

So how to add the details like, region, portalId, formId and optional other fields like email?

I’ve tried to add te custom fields in a seperate js file also i’ve tried via tagmanager to inject them no results.

How can I make my parameters in a nested anonymous function for use in a separate module?

I have a module that contains a function(createForm()) which creates a form when executed. The form created has two text input boxes(for ‘task name’ and ‘task description’) as well as a submit button at the end of the form. The submit button currently console logs the two values entered from the user(userInputForTaskName and userInputForDescription).

In a separate module, I have a function getTaskData() which I call on createForm() then declares two variables(userInputForTaskName and userInputForDescription) which I want to assign the values that were entered and console logged to so that I can use them in a separate function but still in the same module.

How can I make the two values entered by the user in createForm() available for use in a function in a separate module?

This is my current createForm function:

export function createForm(onSubmit) {
    // CREATES <FORM>
    const form = createFormElement();
    // CREATES TEXT INPUT(TEXT BOX) FOR TASK NAME & TASK DESCRIPTION
    const taskNameLabel = createInputLabel('taskName', 'Task Name:');
    const taskNameInputElement = createTextInput('taskName');
    const taskDescriptionLabel = createInputLabel('taskDescription', 'Task Description:');
    const taskDescriptionInputElement = createTextInput('taskDescription');
    // CREATES SUBMIT BUTTON
    const submitButton = createSubmitButtonInput(
        taskNameInputElement, 
        taskDescriptionInputElement, 
        function(userInputForTaskName, userInputForDescription) {
            console.log(userInputForTaskName)
            console.log(userInputForDescription)
            
            taskNameLabel.remove();
            taskNameInputElement.remove();
            taskDescriptionLabel.remove();
            taskDescriptionInputElement.remove();
            submitButton.remove();

            return userInputForTaskName, userInputForDescription;
    });

In my current getTaskData() function, I call on createForm() to create the form, then I declare two variables(userInputForTaskName and userInputForDescription) and assign the values createForm.userInputForTaskName and const userInputForDescription = createForm.userInputForDescription; to them. At the end of the function, I created an alert for alert(createForm.userInputForDescription); to see if it’s working but the alert never executes leading me to think that the function ends when the submit button is clicked and that the user inputted data never makes it back to the getTaskData() function.

Stringify object hook dependency array issue

There are issues when it comes to dependency array giving inconsistent data when using value stringify in dependency array. When I filtered the data by cities the charts fails to filter out data when y variable is the same. Say for example I was filtering meetings in Tokyo, JP with 2 meetings and it will not change dot plot horizontally to current city to say Toronto, CN which also has 2 meetings. This is consistent inconsistency in the data whenever you have the city with the same number of objects, fails to notice the change in content of those objects fyi city name reference.

APP Main Component Code

import React from 'react';
import { useEffect, useState } from 'react';
import CitySearch from './components/CitySearch';
import EventList from './components/EventList';
import NumberOfEvents from './components/NumberOfEvents'
import { getEvents, extractLocations } from './api';
import './App.css';
import { CityAlert, NumberAlert, EventAlert } from './components/Alert';
import CityEventsChart from './components/CityEventsChart';
import EventGenresChart from './components/EventGenresChart';

const App = () => {
  const [events, setEvents] = useState([]);
  const [allLocations, setAllLocations] = useState([]);
  const [currentCity, setCurrentCity] = useState("See all cities");
  const [currentNOE, setCurrentNOE] = useState(32);
  const [cityAlert, setCityAlert] = useState("");
  const [numberAlert, setNumberAlert] = useState("");
  const [eventAlert, setEventAlert] = useState("");
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  // const [defaultFiltered, setDefaultFiltered] = useState("")

  const updateOnlineStatus = () => {
    const online = navigator.onLine;
    setIsOnline(online);
    setEventAlert(online ? "" : "Currently viewing Offline Database");
  };
  useEffect(() => {
    updateOnlineStatus();
    fetchData();
    window.addEventListener("online", updateOnlineStatus);
    window.addEventListener("offline", updateOnlineStatus); 
    return () => {
      window.removeEventListener("online", updateOnlineStatus);
      window.removeEventListener("offline", updateOnlineStatus);
    };
  }, [currentCity, currentNOE]);

  const fetchData = async () => {
    const allEvents = await getEvents();
    const filteredEvents = currentCity === "See all cities" ?
      allEvents :
      allEvents.filter(event => event.location === currentCity)
    setEvents(filteredEvents.slice(0, currentNOE));
    setAllLocations(extractLocations(allEvents));
  }

  return (
    <div className="App">
      <h1 data-testid="outside-element">Meetup App</h1>
      <img className="time" alt="meet-logo" src='/calendar.png'></img>
      <div className="cityError-Message">
        {eventAlert.length ? <EventAlert text={eventAlert}/> : null}
      </div>
      <CitySearch 
        allLocations={allLocations} 
        setCurrentCity={setCurrentCity} 
        setCityAlert={setCityAlert} 
      />

      <div className="cityError-Message">
        {cityAlert.length ? <CityAlert text={cityAlert}/> : null}
      </div>
      <NumberOfEvents 
        currentNOE={currentNOE}
        setCurrentNOE={setCurrentNOE}
        setNumberAlert={setNumberAlert}
      />
      <div className="cityNumber-Message">
        {numberAlert ? <NumberAlert text={numberAlert}/> : null}
      </div>
      <div className="charts-container">
      <EventGenresChart
      events={events}
      />
      <CityEventsChart 
      allLocations={allLocations} 
      events={events} 
      />
      </div>
      <EventList 
        events={events} 
        setEventAlert={setEventAlert}
      />
    </div>
  );
}

export default App;
import mockData from './mock-data';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';  // Include the CSS for styling

export const getAccessToken = async () => {
  const accessToken = localStorage.getItem('access_token');
  const tokenCheck = accessToken && (await checkToken(accessToken));

  if (!accessToken || tokenCheck.error) {
    await localStorage.removeItem("access_token");
    const searchParams = new URLSearchParams(window.location.search);
    const code = await searchParams.get("code");
    if (!code) {
      const response = await fetch(
        "https://pp3rdn62qf.execute-api.us-east-1.amazonaws.com/dev/api/get-auth-url"
      );
      const result = await response.json();
      const { authUrl } = result;
      return (window.location.href = authUrl);
    }
    return code && getToken(code);
  }
  return accessToken;
};

export const extractLocations = (events) => {
  const extractedLocations = events.map((event) => event.location);
  const locations = [...new Set(extractedLocations)];
  return locations;
};

const checkToken = async (accessToken) => {
  const response = await fetch(
    `https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${accessToken}`
  );
  const result = await response.json();
  return result;
 };
 
 const removeQuery = () => {
  let newurl;
  if (window.history.pushState && window.location.pathname) {
    newurl =
      window.location.protocol +
      "//" +
      window.location.host +
      window.location.pathname;
    window.history.pushState("", "", newurl);
  } else {
    newurl = window.location.protocol + "//" + window.location.host;
    window.history.pushState("", "", newurl);
  }
 };
 
export const getEvents = async () => {
  if (window.location.href.startsWith("http://localhost")) {
   return mockData;
  }
  if (!navigator.onLine) {
    const events = localStorage.getItem("lastEvents");
    NProgress.done();
    return events?JSON.parse(events):[];
  }
  const token = await getAccessToken();
  if (token) {
    removeQuery();
    const url =  "https://pp3rdn62qf.execute-api.us-east-1.amazonaws.com/
    dev/api/get-calendar- events" + "/" + token;
    const response = await fetch(url);
    const result = await response.json();

if (result) {
NProgress.done();
localStorage.setItem("lastEvents", JSON.stringify(result.events));
return result.events;
  } else {
    return null;
  }
};
return null;
};

const getToken = async (code) => {
  try {
    const encodeCode = encodeURIComponent(code);
 
const response = await fetch( 'https://pp3rdn62qf.execute-api.us-east-1.amazonaws.com/dev/api/token' + '/' + encodeCode);
if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`)
}
const { access_token } = await response.json();
access_token && localStorage.setItem("access_token", access_token);
return access_token;
  } catch (error) {
    error.json();
  }
 }

src/components/CityEventsChart.jsx

import React, { useState, useEffect } from 'react';
import {
  ScatterChart,
  Scatter,
  XAxis, YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Label
} from 'recharts';   

const CityEventsChart = ( {allLocations, events}  ) => {
  const [data, setData] = useState([]);
  const getData = () => {
    const data = allLocations.map((location) => {
      const countnumber = events.filter((event) => event.location === location).length
      const city = location.split((/, | - /))[0]
      return { city, countnumber };
    })
    return data;
  };
  useEffect(() => {
    setData(getData());
  }, [JSON.stringify(events)]);// this works consistantly 

   // [`${events}`]) SAME NUMBER OBJECTS = SAME ARRAY WHEN VALUE SHOULD OF CHANGED CF PLEASE   INVESTIGATE
   
  return (
    <ResponsiveContainer width="50%" height={400}>
      <ScatterChart
        margin={{
          top: 100,
          right: 50,
          bottom: 100,
          left: 40,
        }}
      >
        <CartesianGrid />
        <XAxis type="category" dataKey="city" name="City"
          angle={60} interval={0} tick={{ dx: 20, dy: 40, fontSize: 14 }} >
        <Label value="Cities" offset={-70} position="insideBottom" />
        </XAxis>
        <YAxis type="number" dataKey="countnumber" name="Meetings" allowDecimals={false} >
        <Label value="Number of Meetings" offset={-120} position="insideLeft" />
        </YAxis>
        <Tooltip cursor={{ strokeDasharray: '3 3' }} />
        <Scatter name="A school" data={data} fill="#8884d8" />
     </ScatterChart>
    </ResponsiveContainer>
  );
}

export default CityEventsChart;

Event Genres Chart

import React from 'react';
import { PieChart, Pie, Cell, ResponsiveContainer, Legend } from 'recharts';
import { useEffect, useState} from 'react';

const EventGenresChart = ({ allLocations, events }) => {
  const [data, setData] = useState([]);
  const genres = ['React', 'JavaScript', 'Node', 'jQuery', 'Angular' ];
  const COLORS = ['#0088FE','#00C49F','#FFBB28','#FF8042','#8884d8'];
  const getData = () => {
    const data = genres.map((genre) => {
      const filteredEvents = events.filter(event => event.summary.includes(genre));      
      return {
        name: genre,
        value: filteredEvents.length
      }
    })
    return data;
  };
  useEffect(() => {
    setData(getData());
  }, [JSON.stringify(events)]);// this works consistantly 
  
  
 // [`${events}`]) SAME NUMBER OBJECTS = SAME ARRAY WHEN VALUE SHOULD OF CHANGED CF PLEASE  INVESTIGATE
  
return (
    <ResponsiveContainer width="50%" height={400}>
      <PieChart width={400} height ={400} >
        <Pie
            data={data}
            labelLine={false}
            outerRadius={125}
            fill="#8884d8"
            dataKey="value"
            label="name"
        >
            {data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
            ))}
        </Pie>
        <Legend verticalAlign="bottom" height={36}/>
      </PieChart>
    </ResponsiveContainer>
  );
}

export default EventGenresChart;

City Search component

import React from 'react';
import { useState, useEffect, useRef } from "react";
import '../../src/App.css';

const CitySearch = ({ setCurrentCity, allLocations,  
setCityAlert}) => {
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [suggestions, setSuggestions] = useState(allLocations);
  const SuggestionListRef = useRef(null);
  const [eventAlert, setEventAlert] = useState("");
  const [query, setQuery] = useState("");

  const handleInputChanged = (event) => {
    const value = event.target.value;
    setQuery(value); // Always reflect what's typed
  
    const trimmedValue = value.trim();
  
    // Filter suggestions based on input
    const filteredSuggestions = allLocations.filter((location) 
=>    
location.toLowerCase().includes(trimmedValue.toLowerCase())
    );
  
    if (filteredSuggestions.length === 0) {
      setSuggestions([]);
      setCityAlert("We can not find the city you are looking 
      for. Please try another city.");
    } else {
      setSuggestions(filteredSuggestions);
      /// setCityAlert(""); CANNOT FIND FUNCTION DON'T GET 
      WHY!!!!
    }
    setShowSuggestions(true);
  };

  const handleItemClicked = (event) => {
    const value = event.target.textContent;
    setQuery(value);
    setShowSuggestions(false); // Hide suggestions
    setCurrentCity(value);
    setEventAlert("");
  };

  // Handle clicking outside the dropdown
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (SuggestionListRef.current && 
!SuggestionListRef.current.contains(event.target)) {
        setShowSuggestions(false); // Hide suggestions when 
    clicking outside
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", 
handleClickOutside);
    };
  }, [`${allLocations}`]);

  return (
    <div id="citySearch" data-testid="city-search">
        <h3>Choose your nearest city</h3>
      <input
        type="text"
        className="city"
        placeholder="Search City for meetings"
        value={query}


        onFocus={() => {
          if (query.trim() === "") {
            setSuggestions(allLocations);
          }
          setShowSuggestions(true);
        }}
        onChange={handleInputChanged}
        data-testid="search-input"
        />
      {showSuggestions && (
        <ul data-testid="CityList" className="suggestions" ref=. 
      {SuggestionListRef}>
          <div className="listCities">
            {suggestions.map((suggestion, index) => (
              <li
                className="cityName"
                onClick={handleItemClicked}
                key={`${suggestion}-${index}`}
              >
                {suggestion}
              </li>
            ))}
            <li
              className="cityName"
              key="See all cities"
              onClick={handleItemClicked}
            >
              <b>See all cities</b>
            </li>
          </div>
        </ul>
      )}
    </div>
  );
};

export default CitySearch;

Number of Events Component

import React from 'react';
import { useState } from "react";
import '../App.css';

const NumberOfEvents = ({setCurrentNOE, currentNOE, 
setNumberAlert }) => {
    const handleInputChanged = (event) => {
        const value = event.target.value;

        // Convert value to a number if it's a valid numeric 
        string
        const numericValue = Number(value);

        setCurrentNOE(value);

        // Validate the input
        if (isNaN(numericValue)) {
            setNumberAlert('Enter a valid number');
        } else if (numericValue < 1) {
            setNumberAlert('Number must be greater than 0');
        } else if (!Number.isInteger(numericValue)) {
            setNumberAlert('Input must be a whole number')
        }
        else
        {
            setNumberAlert('');
            setCurrentNOE(numericValue); // Update the main 
            state only when input is valid
        }
    };

    return (
        <div id="numberSearch" data-testid="number-of-events">
            <h5>Number of Events:</h5>
                <input 
                    className="eventNumber"
                    type="number"
                    value={currentNOE}
                    role="textbox"
                    onChange={handleInputChanged}
                    data-testid="NumberOfEventsInput"
                />
        </div>
    );
};

export default NumberOfEvents;

src/components/EventList.js

import React from 'react';
import Event from "./Event";
import '../../src/App.css';
const EventList = ({ events }) => {
 return (
   <ul className="event-list" data-testid="event-list">
     {events ?
       events.map(event => <Event key={event.id} event={event} 
         />) :
     null}
   </ul>
 );
}

export default EventList;

src/components/Event.js

import React from 'react';
import Button from './Button'
import '../../src/App.css';

const Event = ({ event }) => {
  return (
    <li className="event">
      <h3>{event.summary}</h3>
      <p className="eventAttribute">{event.start.dateTime}</p>
      <p className="eventAttribute">{event.end.dateTime}</p>
      <p className="eventAttribute">{event.location}</p>
      <Button event={event} />
    </li>
  );
}
  
export default Event;

How to replace require statement with import statement

I am struggling to get some sample code to work for learning purposes. This is the first two lines of code. How do I convert that to a simple javascript that will load the packages?

const tf = require('@tensorflow/tfjs');
const speechCommands = require('@tensorflow-models/speech-commands');

Clearly those are two packages on NPM, and I have downloaded them via NPM, but I don’t get how I am then supposed to use the packages in the javascript.

It seems like I should be able to download them, put them in a directory, and then import them. But I have not been able to get this to work.

import {tf} from @tensorflow/tfjs;
import {speechCommands} from @tensorflow-models/speech-commands;

This is where it comes from.

How is this site blocking .click() while allowing actual mouse clicks?

A site has a series of coupon buttons, each with a unique id. From the dev console, if I run document.getElementById('couponAddBtn1234').click() nothing happens. But if I manually click the button with the mouse, it triggers the button action.

I’ve tried triggering .click() on the parent element and also dispatching events for mousedown, mouseup and click but nothing works.

What magic is this site using to block/detect programmatic button clicks?

Markup of button element

How do I Implement “speaker_wav” for “tts-server” (coqui-ai), in a JavaScript API call

I am trying to send a “POST” request to the tts-server API, found at the endpoint “http://localhost:5002/api/tts”.

In the past I have had no issues working with the voices that don’t require an additional audio file to process. I.e. “tts_models/en/jenny/jenny”.

But my new requirements specifiy that I need to use xtts with a “speaker_wav” file to “clone” a voice.

Before when I used the “jenny” voice I used to have the “text” argument within a query string, so: “http://localhost:5002/api/tts?text=”${customText}””. Which I have tried adding the path for the speaker_wav to the query string, but it doesn’t seem to be looking there.

Next I tried moving everything into a body, with a JSON.stringify. That also doesn’t seem to want to work. I tried converting the data to a FormData object. Also didn’t work. And I even tried having the “text” in the query string with the “speaker_wav” and “language_idx” in the body with their values.

Now I am able to get this working with the “tts-server” terminal tool. For which I used this line:

tts --model_name tts_models/multilingual/multi-dataset/xtts_v2 --text "Testing, 1 2 3..." --speaker_wav "C:UserspersoDownloadsPhonetic SentenceConvertedspeaker.wav" --language_idx en

Which worked perfectly fine, but I am looking to avoid the spin up that comes from each one of those calls, where you include the “text”. The app is going to be running a good amount of these API calls, so that extra spin up time is going to total up fast.

If there is a way to include the “speaker_wav” file in the initial terminal call. To get the server running on “http://localhost:5002”. Then that would work too. Here is my current bat file that is used to call the “tts-server”:

set TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1

echo TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=%TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD%

"C:Userspersominiconda3envsTTSScriptstts-server.exe" --model_path "C:UserspersoAppDataLocalttstts_models--multilingual--multi-dataset--xtts_v2" --config_path "C:UserspersoAppDataLocalttstts_models--multilingual--multi-dataset--xtts_v2config.json"

Please feel free to ask any questions if I have not given enough information. I am unable to provide specifics due to the nature of the app. But I will try and reword to give the best possible information.

MudBlazor Drag&Drop between MudTable and MudDropZone

I have the razor page (with MudBlazor) with a MudTable at the top. The table displays . Beneath that, I have a grid of MudDropZones, rooms as columns and roles as rows. I called it . So a person has a duty in a room at a role. Existing Duties, you can successfully drag&drop inside the grid. But I want to create new Duties by grabbing a person from the MudTable and dragging it into the grid…. doesn’t work.The ItemDropped method does not fire. The cherry on top would be, if the dragged duty would be displayed as if the drag would have been started inside the grid.

Here is my minimalized Code:

@page "/duty2"

@* No marking while Drag&Drop *@
<div class="@(_isDragging ? "no-select" : "")">
    @* No scroll while Drag&Drop *@
    <div style="@(_isDragging ? "overflow: hidden; height: 350px;" : "overflow: auto; height: 350px;")">
        <MudTable Items="@_persons"
        Dense="true"
        Hover="true"
        Bordered="true"
        Striped="true"
        Virtualize="true"
        FixedHeader="true"
        Filter="new Func<Person,bool>(FilterFunc1)"
        SortLabel="Sort By"
        Loading="@_loading"
        @bind-SelectedItem="selectedItem1"
        Class="mud-table-sticky-header">
            <ToolBarContent>
                <MudText Typo="Typo.h6">Personen</MudText>
                <MudSpacer />
                <MudTextField @bind-Value="searchString1" Placeholder="Search"
                Adornment="Adornment.Start"
                AdornmentIcon="@Icons.Material.Filled.Search"
                IconSize="Size.Medium"
                Immediate="true"
                Class="mt-0" />
            </ToolBarContent>
            <HeaderContent>
                <MudTh><MudTableSortLabel SortBy="new Func<Person, object>(x=>x.PersonId)">ID</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortBy="new Func<Person, object>(x=>x.Lastname)" InitialDirection="SortDirection.Ascending">Lastname</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortBy="new Func<Person, object>(x=>x.Firstname)">Firstname</MudTableSortLabel></MudTh>
            </HeaderContent>
            <RowTemplate>
                <MudTd DataLabel="ID">
                    <div draggable="true" @ondragstart="e => OnOfficialDragStart(e, context)" style="cursor: grab;">@context.PersonId</div>
                </MudTd>
                <MudTd DataLabel="Lastname">
                    <div draggable="true" @ondragstart="e => OnOfficialDragStart(e, context)" style="cursor: grab;">@context.Lastname</div>
                </MudTd>
                <MudTd DataLabel="Firstname">
                    <div draggable="true" @ondragstart="e => OnOfficialDragStart(e, context)" style="cursor: grab;">@context.Firstname</div>
                </MudTd>
            </RowTemplate>
        </MudTable>
    </div>

    <MudDivider DividerType="DividerType.Middle" Class="my-6" />

    @if (_rooms == null)
    {
        <p>Loading...</p>
    }
    else
    {
        <MudDropContainer T="Duty"
        Items="_duties"
        ItemsSelector="@((item, dropzone) => item.Identifier == dropzone)"
        ItemDropped="ItemDropped"
        ItemRenderer="@DutyRenderer"
        Class="duty-table-container">

            <ChildContent>
                <table class="duty-table">
                    <thead>
                        <tr>
                            <th class="header-cell"></th>
                            @foreach (Room comp in _rooms)
                            {
                                <th class="header-cell" style="background-color:@comp.Color">@comp.Name</th>
                            }
                        </tr>
                    </thead>

                    <tbody>
                        @foreach (var role in _roles)
                        {
                            <tr>
                                <!-- Rowheader -->
                                <td class="role-cell">@role.Label</td>

                                @foreach (Room comp in _rooms)
                                {
                                    string identifier = $"{role.Id};{comp.RoomId}";
                                    <td class="dropzone-cell">
                                        <MudDropZone T="Duty" Identifier="@identifier" Class="mud-dropzone-box" />
                                    </td>
                                }
                            </tr>
                        }
                    </tbody>
                </table>
            </ChildContent>
        </MudDropContainer>



    }
</div>

@code {
    private string searchString1 = "";
    private bool _loading = false;
    private Person selectedItem1 = null;
    private HashSet<Person> selectedItems = new HashSet<Person>();
    private List<Person> _persons = new List<Person>();


    private List<Room> _rooms = new();
    private List<Duty> _duties = new();
    private RenderFragment<Duty> DutyRenderer => duty =>@<div class="duty-chip" style="background-color: @(string.IsNullOrWhiteSpace(duty.Person?.Color) ? "#e3f2fd" : duty.Person.Color);">@duty.Person?.Firstname<br />@duty.Person?.Lastname</div>;
    private bool _isDragging = false;
    private record Role(int Id, string Label);
    private List<Role> _roles = new() {
        new Role(1, "TL"),
        new Role(2, "BS"),
        new Role(3, "PR"),
        new Role(4, "MU"),
    };


    protected override async Task OnInitializedAsync()
    {
        _loading = true;
        _persons = new()
        {
            new Person() { PersonId = 1, Lastname = "Kirk", Firstname = "James T.", Color = "#2590ff;" },
            new Person() { PersonId = 2, Lastname = "McCoy", Firstname = "Leonard", Color = "#326711;" },
            new Person() { PersonId = 3, Lastname = "Scott", Firstname = "Montgomery", Color = "#87ab6c;" },
            new Person() { PersonId = 4, Lastname = "Uhura", Firstname = "Nyota", Color = "#f8f1cc;" },
            new Person() { PersonId = 5, Lastname = "Sulu", Firstname = "Hikaru", Color = "#54f834;" }
        };
        _loading = false;

        _rooms = new()
        {
            new Room() { RoomId = 1, Name = "R1", Color = "#889900;" },
            new Room() { RoomId = 2, Name = "R2", Color = "#9944cc;" },
            new Room() { RoomId = 3, Name = "R3", Color = "#00ff56;" },
            new Room() { RoomId = 4, Name = "R4", Color = "#cf2233;" }
        };

        _duties = new()
        { 
            new Duty(){ DutyId = 1, RoomId = 1, RoleId = 1, PersonId = 1, Person = new Person() { PersonId = 1, Lastname = "Kirk", Firstname = "James T.", Color = "#2590ff;" } },
            new Duty(){ DutyId = 1, RoomId = 2, RoleId = 4, PersonId = 2, Person = new Person() { PersonId = 2, Lastname = "McCoy", Firstname = "Leonard", Color = "#326711;" } },
            new Duty(){ DutyId = 2, RoomId = 3, RoleId = 2, PersonId = 2, Person = new Person() { PersonId = 2, Lastname = "McCoy", Firstname = "Leonard", Color = "#326711;" } },
            new Duty(){ DutyId = 3, RoomId = 2, RoleId = 3, PersonId = 4, Person = new Person() { PersonId = 5, Lastname = "Sulu", Firstname = "Hikaru", Color = "#54f834;" } }
        };
    }

    private bool FilterFunc1(Person element) => FilterFunc(element, searchString1);

    private bool FilterFunc(Person element, string searchString)
    {
        if (string.IsNullOrWhiteSpace(searchString))
            return true;

        string[] search = searchString.Split(" ");

        foreach (string s in search)
        {
            if (element.Firstname.Contains(s, StringComparison.OrdinalIgnoreCase)
                || element.Lastname.Contains(s, StringComparison.OrdinalIgnoreCase))
                continue;
            else
                return false;
        }
        return true;
    }


    private async void OnOfficialDragStart(DragEventArgs e, Person person)
    {
        _isDragging = true;

        Duty duty = new Duty()
            {
                PersonId = person.PersonId,
                RoleId = 0,
                RoomId = 0
            };

        await InvokeAsync(StateHasChanged);
    }

    private void ItemDropped(MudItemDropInfo<Duty> dropItem)
    {
        _isDragging = false;

        string[] dzi = dropItem.DropzoneIdentifier.Split(";");
        dropItem.Item.RoleId = Convert.ToInt32(dzi[0]);
        dropItem.Item.RoomId = Convert.ToInt32(dzi[1]);
    }


    public class Room
    {
        public int RoomId { get; set; }
        public string Name { get; set; }
        public string Color { get; set; }
    }

    public class Duty 
    {
        public int DutyId { get; set; }
        public int PersonId { get; set; }
        public int RoomId { get; set; }
        public int RoleId { get; set; }
        public Person Person { get; set; } 
        public string Identifier => $"{RoleId};{RoomId}";
    }

    public class Person
    {
        public int PersonId { get; set; }
        public string Lastname { get; set; }
        public string Firstname { get; set; }
        public string Color { get; set; }
    }
}

Fetch request to dummyapi.io fails in browser – CORS or app-id issue with vanilla JS?

I’m currently working on a small front-end project where the main goal is to fetch and display employee data from dummyapi.io using JavaScript. I want to create a simple user interface that lists employees with their name, picture, and other basic information, and style everything using CSS.

I’ve set up the fetch call using the required app-id in the headers as instructed by the dummyapi documentation. The structure of my code seems fairly straightforward. I’m using plain JavaScript (no frameworks yet) and standard CSS for styling. The issue I’m facing is that every time I try to make the request, I receive a fetch error in the browser console.

React useControllableState hook as a Vue composable

I am trying to build a component that can either be controlled or uncontrolled and I am trying to mimic how a React library Vaul uses this hook. The drawer component only calls the onChange handler if the component is uncontrolled.

If I try to mimic this behavior with Vue, I can use defineModel with watch but then if the parent controls the state the watcher will fire since the props are reactive.

I am looking for a bare bones example how I can turn this into a Vue composable. I tried returning computed({ get() {}, set()}) from a composable, but I was not able to mimic the same behavior.

const [isOpen = false, setIsOpen] = useControllableState({
    defaultProp: defaultOpen,
    prop: openProp,
    onChange: (o: boolean) => {
      onOpenChange?.(o);

      if (!o && !nested) {
        restorePositionSetting();
      }

      setTimeout(() => {
        onAnimationEnd?.(o);
      }, TRANSITIONS.DURATION * 1000);

      if (o && !modal) {
        if (typeof window !== 'undefined') {
          window.requestAnimationFrame(() => {
            document.body.style.pointerEvents = 'auto';
          });
        }
      }

      if (!o) {
        // This will be removed when the exit animation ends (`500ms`)
        document.body.style.pointerEvents = 'auto';
      }
    },
  });

Here is a React composable for useControllableState

import React from 'react';

type UseControllableStateParams<T> = {
  prop?: T | undefined;
  defaultProp?: T | undefined;
  onChange?: (state: T) => void;
};

type SetStateFn<T> = (prevState?: T) => T;

function useCallbackRef<T extends (...args: any[]) => any>(callback: T | undefined): T {
  const callbackRef = React.useRef(callback);

  React.useEffect(() => {
    callbackRef.current = callback;
  });

  // https://github.com/facebook/react/issues/19240
  return React.useMemo(() => ((...args) => callbackRef.current?.(...args)) as T, []);
}

function useUncontrolledState<T>({ defaultProp, onChange }: Omit<UseControllableStateParams<T>, 'prop'>) {
  const uncontrolledState = React.useState<T | undefined>(defaultProp);
  const [value] = uncontrolledState;
  const prevValueRef = React.useRef(value);
  const handleChange = useCallbackRef(onChange);

  React.useEffect(() => {
    if (prevValueRef.current !== value) {
      handleChange(value as T);
      prevValueRef.current = value;
    }
  }, [value, prevValueRef, handleChange]);

  return uncontrolledState;
}
export function useControllableState<T>({ prop, defaultProp, onChange = () => {} }: UseControllableStateParams<T>) {
  const [uncontrolledProp, setUncontrolledProp] = useUncontrolledState({ defaultProp, onChange });
  const isControlled = prop !== undefined;
  const value = isControlled ? prop : uncontrolledProp;
  const handleChange = useCallbackRef(onChange);

  const setValue: React.Dispatch<React.SetStateAction<T | undefined>> = React.useCallback(
    (nextValue) => {
      if (isControlled) {
        const setter = nextValue as SetStateFn<T>;
        const value = typeof nextValue === 'function' ? setter(prop) : nextValue;
        if (value !== prop) handleChange(value as T);
      } else {
        setUncontrolledProp(nextValue);
      }
    },
    [isControlled, prop, setUncontrolledProp, handleChange],
  );

  return [value, setValue] as const;
}