ReactJS: Extract values from Array of Objects?

After some processing, I get an array of objects similar to this:

0: {key: 1}
1: {key: 0}
2: {key: 1}

I want to extract the values from each object and check to see if a specific value exists among the resulting list of values, for example checking for 0. Can anyone describe how to get all the values into a single list?

How do I get a gif wihtin an Apple Books e-book to touchstart?

I am trying to get a .gif to work via touch start. Specifically, this gif is placed within an e-book intended to work with Apple Books.

I followed the guide here: How to play a gif only on onclick in javascript … This worked great on Windows as well as on Android e-book readers for starting the .gif on click as well as on touch. However, it’s a no-go for Apple Books.

For reference, my e-book creator software (Kotobee Author) allows for JS, HTML, and CSS. Alas, I am new to all of this (obviously).

The working/not working code looks like this:

number = 0;
var animations = ['https://image.ibb.co/epha5A/giphy.gif',
  'https://image.ibb.co/epha5A/giphy.gif',
  'https://image.ibb.co/epha5A/giphy.gif'
];


function character() {

  image = document.getElementById('hiddenimageid');
  image.src = animations[number];
}
.board {
  position: absolute;
  top: 4.3vh;
  left: 10vw;
  cursor: pointer;
}

.board img {
  width: 35.3vw;
  height: 45.5vh;
  border-radius: 15%;
}
<body>
  <div class="board">
    <img src=" https://i.stack.imgur.com/pqbOp.png" id="hiddenimageid" onclick="character();"/>
  </div>
</body>

I tried trading onclick=”character();” with ontouchstart=”character();”

Unfortunately, this didn’t work either. Can somebody guide me as to the correct way to go about making this happen?

How to make image change with hover through javascript only?

Javascript newbie following Ania Kubow’s Javascript bootcamp video / card matching game tutorial (https://youtu.be/Xm4BObh4MhI?t=34702).

I’d like to request some help figuring out how to have an image change when hovered over, specifically within the Javascript code. For context, I’m making a card matching game based on the tutorial above, except it’s Pokemon themed. When the card/open Pokeball is hovered over, it should then change to a half-way closed Pokeball to show that it’s almost selected.

What’s in the HTML file in this section is literally just:

            <div class="section2"></div>

So it’s all in the Javascript where all of this comes from. Here is the main function. (Bolded is what I added myself.

    function createBoard() {
        for (let i = 0; i < cardArray.length; i++) {
        const card = document.createElement('img')
        card.setAttribute('src', 'src/images/pokeballOpen.png')
        card.setAttribute('data-id', i)
        card.addEventListener('click', flipCard)
**        card.addEventListener('mouseover', hoverPokeball)
        card.addEventListener('mouseout', unhoverPokeball)**
        container.appendChild(card)
        }
    }

Then I also have:

    function hoverPokeball() {
        card.setAttribute('src', 'src/images/pokeballMid.png')
    }

    // unhover over pokeball
    function unhoverPokeball() {
        card.setAttribute('src', 'src/images/pokeballOpen.png')
    }

I am 100% missing something simple here, and I would appreciate it if any of you could help me out.

How can I make the TextField open as long as the button is clicked?

I am having a trouble here, I created a choices wherein if the user clicked the Other's button, the TextField will be open, but the problem is, when I click the Others button again, it will not closed.

What I want here is keep the TextField Open, as long as the button is highlighted and close it when the user unclicked` it

In this image, I clicked it, so It will open

First Image

But when I clicked it again.

Second Image

It is still open.

So what I did here is I rendered the Question as well as the Choices, and check if the choices's essay === true, then show the TextField

{
    "_id": "642d892955e310c62e46b9d3",
    "title": "Question Sample",
    "choices": [
        {
            "choices": "GAD Orientation",
            "essay": false,
        },
        {
            "choices": "Gender Sensitivity Training",
            "essay": false,
        },
        {
            "choices": "Gender Mainstreaming",
            "essay": false,
        },
        {
            "choices": "GAD Planning and Budgeting",
            "essay": false,
        },
        {
            "choices": "GAD Analysis Tools",
            "essay": false,
        },
        {
            "choices": "Harmonized Gender and Development Guidelines",
            "essay": false,
        },
        {
            "choices": "Gender Mainstreaming Evaluation Framework",
            "essay": false,
        },
        {
            "choices": "Others, enumerate",
            "essay": true,
        },
        {
            "choices": "None",
            "essay": false,
        }
    ],
    "type_of_question": true,
}

So what I did here is, I checked the choice.essay === true then Open it.
Part4.js

  const [openChoiceId, setOpenChoiceId] = useState(null);
  const handleClick = (choice) => {
    if (choice.essay === true) {
      setOpenChoiceId(choice.choices);
    } else {
    }
  };


{currentChoices.map((choice, index) =>(
                  <Grid item xs={6} key={index}>
                   <label className="toggle-button" key={choice.id} onClick={() => handleClick(choice)}>
                   <input className="toggle-button__state" type="checkbox" name="choice" value={choice.choices} onChange={handleChange}/>
                   <span className="toggle-button__text">{choice.choices}</span>
                   
                   <Box sx={{position:'absolute', bottom: 50, left: 0, width: '100%', px: 2}}>
                   {openChoiceId === choice.choices && choice.essay === true && 
                   <TextField
                    id="filled-multiline-static"
                    label="Others"
                    fullWidth
                    multiline
                    rows={3}
                    name="essay" onChange={handleTextFieldChange} 
                    variant="outlined"
                  />}

                   </Box>

                 </label>
                  </Grid>
                  
              ))}

How to implement Short Polling method in Next 13 Server Component

I am currently making an API fetching every 3000ms using setInterval method, I noticed the component doesn’t re-render with latest data. Below is the code block

const Home = async () => {
 let customers = await getCustomers();
 setInterval(async () => customers = await getCustomers(), 3000);
}

return <>
 {customers.map(customer => (<p>{customer.name}<p>))}
</>

Currently the page doesn’t update itself unless I manually refresh the page which is bad in UX perspective. Any seniors have any idea on how to make proper polling to backend using server components?

I did trying normal console logging, which it works when I replace the code expression inside setInterval method with console logs. I understand if it’s client component it re-render the whole component using useEffect() but since this is the main root component, it has to be the server component by default in Next 13.

Name of an algorithm that does dynamic value mapping on a scaling min/max basis?

First off, I’m wondering if there’s already an algorithm or a JS library that already solves the logic/problem I’m currently working on.

I’m working on an interactive project that uses generated data points from I/O sensors. The data points fluctuate between 0 and 100 (as an example). I need a function that will return a value that re-maps the value of the average of all the data points from one range to another while having dynamic floor and ceiling mapping values… Typically mapping functions would re-map a value between 0 to 100 into a value between 0 to 1 respectively. I’m looking for the best way so while the input values could range between 0 and 100, if the data points only range from 35-75, I would want the mapped value to be weighed as if those values were between 0 – 100. Is it like dynamic proportionate scaling or mapping?

It seems like this might be a problem that could already have been solved or have a standard algorithm to solve this logic… but I just don’t know what it’s called.

The parameters needed would be along the following lines:

  • accepts a value that ranges between 0 and 100
  • these values are stored in a dynamic array
  • the values stored in the dynamic array are mapped to return a value between 0 and 1
  • The mapped value needs to consider the fluctuating values max/min values stored in the array.
  • the returned mapped value should adjust and account for the changing floor and ceil values used in the map function as these floor / ceil values are sourced from the min and max data points stored in the array.

Is there an algo or mathematic equation that exists to calculate simular logic? If not, I’d be interested in hearing some potential best solutions or logic for solving this?

Thanks!

Save a picture from a camera feed in the same path as the js script

I’m using vs code to run a local server that uses the faceapi JavaScript library to detect faces in a video stream from the user’s camera. It loads the necessary models for face detection and displays the real-time video with detected faces on a canvas element. It also provides a button to capture a screenshot of the video stream with detected faces and save it as a PNG file. The image file will be saved in automatically in the downloads folder. Is thee a way to save the captured image in the same directory as the JavaScript file.

const screenshotButton = document.getElementById('screenshotButton');

Promise.all([
  faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
  faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
  faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
  faceapi.nets.faceExpressionNet.loadFromUri('/models')
]).then(startVideo);

function startVideo() {
  navigator.getUserMedia(
    { video: {} },
    stream => video.srcObject = stream,
    err => console.error(err)
  );
}

video.addEventListener('play', () => {
  const canvas = faceapi.createCanvasFromMedia(video);
  document.body.append(canvas);
  const displaySize = { width: video.width, height: video.height };
  faceapi.matchDimensions(canvas, displaySize);
  setInterval(async () => {
    const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions();
    const resizedDetections = faceapi.resizeResults(detections, displaySize);
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
    faceapi.draw.drawDetections(canvas, resizedDetections);
  }, 100);

  screenshotButton.addEventListener('click', async () => {
    const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions();
    if (detections.length > 0) {
      const canvas = faceapi.createCanvasFromMedia(video);
      document.body.append(canvas);
      const displaySize = { width: video.width, height: video.height };
      faceapi.matchDimensions(canvas, displaySize);
      const resizedDetections = faceapi.resizeResults(detections, displaySize);
      canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
      faceapi.draw.drawDetections(canvas, resizedDetections);
      const context = canvas.getContext('2d');
      context.drawImage(video, 0, 0, canvas.width, canvas.height);
      const dataURL = canvas.toDataURL('image/png');
      const link = document.createElement('a');
      link.download = `screenshot-${new Date().toISOString()}.png`;
      link.href = dataURL;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      document.body.removeChild(canvas); // Remove the canvas after taking the screenshot
    } else {
      alert('No face detected in the video. Please position your face in front of the camera and try again.');
    }
  });
});

How to keep users viewport scrolled to the right after a component is rerendered in Blazor?

Here’s the Mudblazor ‘pen’ containing the default code provided from the MudBlazor dropzone docs with a few changes. Namely a JavaScript call for when the viewport expands on the x axis. I want to keep the add column box focused in the viewport.

https://try.mudblazor.com/snippet/wkcdYSuLarxRtppw

I’ve had to comment out the scrolltoRightmost(); call as I can’t include the <script> call inside the ‘pen’ for demo purposes.

When a new column is added during OnValidSectionSubmit, I call await ScrollToRightmost();

private async void OnValidSectionSubmit(EditContext context)
{
    _sections.Add(new KanBanSections(newSectionModel.Name, false, String.Empty));
    newSectionModel.Name = string.Empty;
    _addSectionOpen = false;
    await ScrollToRightmost();
}

ScrollToRightmost invokes my JavaScript call.

private async Task ScrollToRightmost()
    {
        await JSRuntime.InvokeVoidAsync("scrollToRightmost", "kanban-container");
    }

Here is the JavaScript for the call to scroll the viewport right to its max-width.

function scrollToRightmost(containerId) {
    console.log("scrollToRightmost called with container ID:", containerId);
    const container = document.getElementById(containerId);
    if (container) {
        console.log("container found:", container);
        container.scrollLeft = container.scrollWidth;
    } else {
        console.log("container not found");
    }
}

The current implementation performs poorly, it fails to scroll the entire viewport width. It is probable that an aberrant Blazor lifecycle event is causing this anomaly, such as a delay in updating the DOM. Still, I’m not certain!

scroll event of out of the document flow

How to listen for the scroll event of an element that is out of the document flow? Are there any other solutions besides implementing a custom scrollbar?

Please tell me how to listen for the scroll event of an element that is out of the document flow.

API response not being saved to a useState()

I’m working on a react native weather app project. I am using openWeatherMapAPI and opencagedata for geolocation. First, Im calling the getGeo() function that takes in the city and stores the lat and lon from the API. Next, to get the actual weather data, I am calling the getWeatherData() function that makes the request to the API that uses the lat and lon for the location and stores the JSON data in the weatherData useState().

This all seems like it should work, but it does not. I have the functions run once a button is pressed getGeo() --> getWeatherData() but I end up needing to press the button 3 times to get any data to be saved to the weatherData .

CODE:

  async function getGeo(){
    fetch(`https://api.opencagedata.com/geocode/v1/json?q=${city}&key=${geoApi}`)
    .then((response) => response.json())
    .then((data) => {
        setGeoData(JSON.stringify(data));
        setLat(data.results[0].geometry.lat)
        setLon(data.results[0].geometry.lng)
    })
    .catch((error) => {
        // Handle any errors that occur
        alert(error);
    });
  }

  async function getWeatherData() {
    fetch(`https://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&exclude=minutely&appid=${weatherApi}&units=metric`)
    .then((response) => response.json())
    .then((data) => {
        setWeatherData(JSON.parse(JSON.stringify(data)));
    })
    .catch((error) => {
        // Handle any errors that occur
        alert(error);
    });
  }


function onPress() {
    // hide the keyboard
    Keyboard.dismiss();
    // get the lat and lon
    getGeo();
    // get weather data
    getWeatherData()
    console.log(weatherData)
    }
  }

To fix my problem I tried to use async and await functions thinking the code was moving on before the weather API could respond to the request. when I did this I didn’t solve my problem the same result happened as before. (Needing to press the button 3 times for data to be entered into the weatherData useState)

Error: The dial request has no valid addresses

when I run js-libp2p , I got this error,it seem to has found the peerid,but multiaddr is not right.i don’t know why the multiaddr has two peerid like this’/ip4/127.0.0.1/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ’

  libp2p:connection-manager options: { maxConnections: 10, minConnections: 4, maxEventLoopDelay: Infinity, pollInterval: 2000, autoDialInterval: 10000, inboundConnectionThreshold: 5, maxIncomingPendingConnections: 10, autoDial: true, maxParallelDials: 100, maxDialsPerPeer: 4, dialTimeout: 10000, inboundUpgradeTimeout: 30000, resolvers: { dnsaddr: [AsyncFunction: dnsaddrResolver] }, addressSorter: [Function: publicAddressesFirst] } +0ms
  libp2p:connection-manager:auto-dialler options: {"enabled":true,"minConnections":4,"autoDialInterval":10000} +0ms
  libp2p:transports adding transport @libp2p/tcp +0ms
  libp2p:transports adding transport libp2p/circuit-relay-v1 +0ms
  libp2p:connection-manager started +2ms
  libp2p:transports creating listener for @libp2p/tcp on /ip4/0.0.0.0/tcp/0 +1ms
  libp2p:connection-manager:auto-dialler started +4ms
  libp2p:mdns:query query _p2p._udp.local +0ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
  libp2p:tcp:listener Listening on { address: '0.0.0.0', family: 'IPv4', port: 49601 } +0ms
  libp2p:peer-store:address-book stored provided peer record for 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
  libp2p:connection-manager options: { maxConnections: 10, minConnections: 4, maxEventLoopDelay: Infinity, pollInterval: 2000, autoDialInterval: 10000, inboundConnectionThreshold: 5, maxIncomingPendingConnections: 10, autoDial: true, maxParallelDials: 100, maxDialsPerPeer: 4, dialTimeout: 10000, inboundUpgradeTimeout: 30000, resolvers: { dnsaddr: [AsyncFunction: dnsaddrResolver] }, addressSorter: [Function: publicAddressesFirst] } +46ms
  libp2p:connection-manager:auto-dialler options: {"enabled":true,"minConnections":4,"autoDialInterval":10000} +42ms
  libp2p:transports adding transport @libp2p/tcp +45ms
  libp2p:transports adding transport libp2p/circuit-relay-v1 +0ms
  libp2p:connection-manager started +0ms
  libp2p:transports creating listener for @libp2p/tcp on /ip4/0.0.0.0/tcp/0 +1ms
  libp2p:connection-manager:auto-dialler started +1ms
  libp2p:mdns:query query _p2p._udp.local +42ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +37ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +0ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +1ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +0ms
  libp2p:peer-store:proto-book added provided protocols for 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +0ms
  libp2p:tcp:listener Listening on { address: '0.0.0.0', family: 'IPv4', port: 49602 } +36ms
  libp2p:peer-store:address-book stored provided peer record for 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +17ms
  libp2p:mdns:query responding to query +15ms
  libp2p:mdns:query responding to query +1ms
  libp2p:mdns:query responding to query +1ms
  libp2p:mdns:query responding to query +0ms
  libp2p:mdns:query responding to query +5ms
  libp2p:mdns:query responding to query +1ms
  libp2p:mdns:query peer found 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
  libp2p:mdns discovered peer in mDNS qeury response 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
Peer1 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv discovered: 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/127.0.0.1/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/192.168.1.176/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
  libp2p:peer-store:address-book added multiaddrs for 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +12ms
  libp2p:mdns:query peer found 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
  libp2p:mdns discovered peer in mDNS qeury response 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
Peer1 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv discovered: 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/127.0.0.1/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/192.168.1.176/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
  libp2p:mdns:query peer found 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
  libp2p:mdns discovered peer in mDNS qeury response 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
Peer1 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv discovered: 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/127.0.0.1/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/192.168.1.176/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
  libp2p:mdns:query peer found 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
  libp2p:mdns discovered peer in mDNS qeury response 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
Peer1 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv discovered: 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/127.0.0.1/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/192.168.1.176/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
  libp2p:mdns:query peer found 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
  libp2p:mdns discovered peer in mDNS qeury response 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
Peer1 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv discovered: 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/127.0.0.1/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/192.168.1.176/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
  libp2p:mdns:query peer found 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
  libp2p:mdns discovered peer in mDNS qeury response 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +1ms
Peer1 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv discovered: 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/127.0.0.1/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/192.168.1.176/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
  libp2p:mdns:query peer found 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
  libp2p:mdns discovered peer in mDNS qeury response 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
Peer1 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv discovered: 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/127.0.0.1/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/192.168.1.176/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
  libp2p:mdns:query peer found 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
  libp2p:mdns discovered peer in mDNS qeury response 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ +0ms
Peer1 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv discovered: 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/127.0.0.1/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
Discovered1: /ip4/192.168.1.176/tcp/49601/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ/p2p/12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ
  libp2p:mdns:query peer found 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +1ms
  libp2p:mdns discovered peer in mDNS qeury response 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +1ms
  libp2p:connection-manager dial to PeerId(12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv) +29ms
Peer2 12D3KooWAYVAAk7tWYkKRATq44JvWLAnzinsuNUukVAwyhvvwKbQ discovered: 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv
  libp2p:dialer creating dial target for 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +0ms
  libp2p:peer-store:address-book added multiaddrs for 12D3KooWQgHa4kbF2C9xzwLUhRPtPkWV263x4DCdG72H1trKqDwv +4ms
file:///Users/wangfaguo/Desktop/project/AwesomeProject/nodejs-assets/nodejs-project/node_modules/libp2p/dist/src/connection-manager/dialer/index.js:102
            throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES);
                          ^

Error: The dial request has no valid addresses
    at DefaultDialer.dial (file:///Users/wangfaguo/Desktop/project/AwesomeProject/nodejs-assets/nodejs-project/node_modules/libp2p/dist/src/connection-manager/dialer/index.js:102:27)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async DefaultConnectionManager.openConnection (file:///Users/wangfaguo/Desktop/project/AwesomeProject/nodejs-assets/nodejs-project/node_modules/libp2p/dist/src/connection-manager/index.js:306:32)
    at async Libp2pNode.dial (file:///Users/wangfaguo/Desktop/project/AwesomeProject/nodejs-assets/nodejs-project/node_modules/libp2p/dist/src/libp2p.js:256:16) {
  code: 'ERR_NO_VALID_ADDRESSES'
}

it seem to has found the peerid,but multiaddr is not right.

  1. environment

libp2p :v0.43.4
node 18.12.1
npm 8.19.2

  1. code
import { createLibp2p } from 'libp2p'
import { tcp } from '@libp2p/tcp'
import { mplex } from '@libp2p/mplex'
import { noise } from '@chainsafe/libp2p-noise'
import { mdns } from '@libp2p/mdns'
import os from 'os'
import { bootstrap } from '@libp2p/bootstrap'
import { kadDHT } from '@libp2p/kad-dht'
import { gossipsub } from '@chainsafe/libp2p-gossipsub'
import { multiaddr } from '@multiformats/multiaddr'


const createNode = async () => {
  const node = await createLibp2p({
    addresses: {
      listen: ['/ip4/0.0.0.0/tcp/0']
    },
    transports: [
      tcp()
    ],
    streamMuxers: [
      mplex()
    ],
    kadDHT:kadDHT(),
    connectionEncryption: [
      noise()
    ],
    peerDiscovery: [
      mdns()
    ],
    connectionManager: {
      maxConnections:10,
      minConnections: 4,
      dialTimeout: 10e3,
    },
    dialer: {
      dialTimeout: 120000,
    }
  })

  return node
}

;(async () => {
  const [node1, node2] = await Promise.all([
    createNode(),
    createNode()
  ])
  node1.addEventListener('peer:connect', (evt) => {
    console.log('connect to: ', evt.detail.remotePeer.toString())
  })
  node1.addEventListener('peer:disconnect', (evt) => {
    console.log('connect to: ', evt.detail.remotePeer.toString())
  })

  node2.addEventListener('peer:connect', (evt) => {
    console.log('connect to: ', evt.detail.remotePeer.toString())
  })
  node2.addEventListener('peer:disconnect', (evt) => {
    console.log('connect to: ', evt.detail.remotePeer.toString())
  })

  node1.addEventListener('peer:discovery', (evt) => {
    const peer = evt.detail
    console.log(`Peer1 ${node1.peerId.toString()} discovered: ${peer.id.toString()}`)
    
    evt.detail.multiaddrs.forEach((ma) => {
      console.log('Discovered1:',ma.toString())
    })
  })
  node2.addEventListener('peer:discovery', (evt) => {
    const peer = evt.detail
    node2.dial(peer.id)
    console.log(`Peer2 ${node2.peerId.toString()} discovered: ${peer.id.toString()}`)
  })


})();

Why isn’t my hamburger navigation menu showing up?

<head>
<link rel="stylesheet" href="/stylesheet/styles.css"/>
    <script src="https://kit.fontawesome.com/929330f5ee.js"crossorigin="anonymous"></script>
    <script src="js/script.js"></script>
</head>

  <body>
    <header>
      <nav class="navbar">
        <a href="#" class="nav-branding">MYBRAND</a>
        <ul class="nav-menu">
          <li class="nav-item">
            <a href="#" class="nav-link">Home</a>
          </li>
          <li class="nav-item">
            <a href="#" class="nav-link">About</a>
          </li>
          <li class="nav-item">
            <a href="#" class="nav-link">Contact</a>
          </li>
        </ul>
        <div class="hamburger">
          <i class="fa-solid fa-bars"></i>
        </div>
      </nav>
    </header>
</body>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500&display=swap');

*{
    font-family: 'Poppins', sans-serif;
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

header {
    background-color: #E50914;

}


li {
    list-style: none;
}

a {
    color: white;
    font-size: x-large;
    text-decoration: none;
}

.navbar {
    min-height: 70px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 24px;

}

.nav-menu{
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 25px;
}

.nav-link{
    transition: 0.1s ease;
}

.nav-link:hover{
    color: rgb(73, 0, 0);
}

.hamburger{
    display:none;
    cursor: pointer;
}



@media (max-width:800px){
    
   .hamburger{
        display: block;
        color: white;
        font-size: x-large;
      }
    
   .nav-menu{
        position: fixed;
        left: -100%;
        top: 70px;
        gap: 0;
        flex-direction: column;
        background-color: #262626;
        width: 100%;
        text-align: center;
        transition: 0.3s;
      }
    
   .nav-item{
        margin: 16px 0;
      }
    
   .nav-menu.active{
        left: 0;
      }
    }
const hamburger = document.querySelector(".hamburger");
const navMenu = document.querySelector(".nav-menu");

hamburger.addEventListener("click", () => {
  hamburger.classList.toggle("active");
  navMenu.classList.toggle("active");
})

document.querySelectorAll(".nav-link").forEach(n => n.addEventListener("click", () => {
  hamburger.classList.remove("active");
  navMenu.classList.remove("active");
}))

hi, I am trying to convert a navbar into a hamburger menu for mobile screens, but it seems like my hamburger icon shows up but the navigation menu doesn’t…

I have tried everything I have copied the code from a youtube video. The code was working perfectly fine on the video but It seems like its not working for me.

I have just started coding and I’m learning css and html. I have just started learning JS.

Can anyone help me with this issue?

css – Why is this div not properly placed?

I tried putting a fontawesome fullscreen icon on the bottom of this iframe, but the div it’s in (background made green for your convenience) is halfway below the parent div. Here’s the code:
HTML:

<html>
<head>
  <title>funnies</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <script src="https://kit.fontawesome.com/204c1cf7c6.js" crossorigin="anonymous"></script>
</head>

<body>
  <iframe id="game-frame" scrolling="no" frameborder="0" width="75%" height="80%" cellspacing="0" src="https://example.com"></iframe>
   <div id="game-options">
   <b><p class="logo-options">Skool</p></b>
   <div class="icons-options">
   <i class="fa-solid fa-expand" style="color: #ffffff;"></i>
   </div>
   </div>
  <script src="script.js"></script>
</body>
</html>

CSS:

body, html {
  height: 100%;
  width: 100%;
  font-family: Arial;
}
p{
  margin: 0;
}
#game-frame{
  margin: 0 auto;
  display: block;
  border-top: 0.5vw solid black;
  border-left: 0.5vw solid black;
  border-right: 0.5vw solid black;
  border-radius: 1vw 1vw 0px 0px;
}
#game-options{
  max-width: 75%;
  margin: 0 auto;
  border: 0.5vw solid black;
  display: block;
  border-radius: 0px 0px 1vw 1vw;
  color: #ffffff;
  background-color: #000000;
}
.logo-options{
  padding-left: 15px;
}
.icons-options{
  padding-right: 15px;
  margin: 0;
  display: inline-block;
  float: right;
  background-color: #00FF00;
}

What’s wrong? I’m a beginner CSS dev, so (please) don’t downvote. Thanks for any help!

HTML and JavaScript code do not work together properly

For a school project, I am required to take an input from the user with my website I created with HTML code. After the user presses the “add a new book” submit button the JavaScript should be able to store the value entered inside of the variable and alert the user with it, however, it does not work.

I found a temporarily solution which is to remove every single form tag except the first and last one except this messes up the format of my code and I am wondering whether there is a better way of solving this issue. My HTML and JS code are included.

Error Message on VS Code displayed –

Uncaught TypeError TypeError: Cannot read properties of undefined (reading ‘value’)
at addNewBook (c:SchoolGrade 11 Comp SciLibrary AsstaddBook.js:4:45)
at onclick (c:SchoolGrade 11 Comp SciLibrary AsstlibraryInterface.html:61:184)
No debugger available, can not send ‘variables’

P.S. – The file name of the JavaScript file is ‘addBook.JS’ and both HTML and JS files are saved within the same folder. I also included the script tag at the end of the body tag as I have seen online, but it still does not work.

My HTML Code

<!DOCTYPE HTML>
<html>
<head>
    <!--This is the website's tab display to let the user know which tab they are on-->
    <title>Add a New Book</title>
</head>
<body>
    <!--The following code displays the page's heading-->
    <h1><center>Add A New Book</center></h1>
    <br><br>
    <center>
        <!--The following form asks the library technician to input the book's ID #-->
        <form>
            <label for="bookIDNumL">Book ID #:</label>  <input type="number" name="bookIDNumL" id="bookIDNumL" >
        </form>
        <br>
        <!--The following form asks the library technician to input the book's title-->
        <form>
            <label for="bookTitleL">Book Title:</label>  <input type="text" name="bookTitleL" id="bookTitleL" >
        </form>
        <br>
        <!--The following form asks the library technician to input the book's dewey number-->
        <form>
            <label for="deweyNumL">Dewey #:</label>  <input type="number" name="deweyNumL" id="deweyNumL" min="0">
        </form>
        <br>
        <!--The following form asks the library technician to input the book's author's first and last name-->
        <form>
            <label for="authorNameL">Author Name:</label>  <input type="text" name="authorNameL" id="authorNameL">
        </form>
        <br>
        <!--The following form asks the library technician to input the book's type-->
        <form>
            <label for="bookTypeL">Book Type:</label>  <input type="radio" name="bookTypeL" id="nonFiction">  <label for="nonFiction">Non-Fiction</label>  <input type="radio" name="bookTypeL" id="fiction">  <label for="fiction">Fiction</label>  <input type="radio" name="bookTypeL" id="graphicNovel">  <label for="graphicNovel">Graphic Novel</label>
        </form>
        <br>
        <!--The following form asks the library technician to input the book's publication date-->
        <form>
            <label for="pubDateL">Publication Date:</label> <select id="pubDateL" name="pubDateL">
                <option></option>
                <option value="before 2000">Before 2000</option>
                <option value="2001-2005">2001-2005</option>
                <option value="2006-2010">2006-2010</option>
                <option value="2011-2015">2011-2015</option>
                <option value="2016-2020">2016-2020</option>
                <option value="2021-2023">2021-2023</option>
            </select>
        </form>
        <br>
        <!--The following form asks the library technician to upload an image of the book's cover-->
        <form>
            <label for="bookCoverL">Book Cover:</label>  <input type="file" name="bookCoverL" id="bookCoverL" value="Upload Book Cover Image">
        </form>
    </center>
    <br><br>
    <!--The following code creates a "back to the homepage" as well as a "add a new book" button to allow the library technician to either go back to the homepage or to add the book with the given information above-->
    <form>
        <input type="submit" value="Back to the Homepage" style="height:50px; width:325px; font-size:30px;">
    </form>
    <form>
        <input onclick = "addNewBook(this.form)" type="submit" value="Add A New Book" style="float:right; height:50px; width:250px; position:relative; top:-50px; font-size:30px;">
    </form>
    <!--The following code creates the images on the top right and left of the webpage-->
    <img src="https://pbs.twimg.com/profile_images/665225941057036288/xXpVpaZ__400x400.png" style="float:right; position:relative; top:-475px; left:275px; height:250px; width:250px;">
    <img src="https://pbs.twimg.com/profile_images/665225941057036288/xXpVpaZ__400x400.png" style="float:right; position:relative; top:-475px; left:-750px; height:250px; width:250px;">
    <script type="text/javascript" src="addBook.js"></script>
</body>
</html>

My JS Code

var libTechBookNum;

function addNewBook(addBookForm) {
libTechBookNum = addBookForm.bookIDNumL.value;
alert(libTechBookNum);
}

React Learning Time [closed]

Let me tell in how much time you learn react js

Time required to learn react js. I want to learn react from which source I should learn it . If video tutorial of updated react available then share please