How do I fix the issue with my React Todo Counter not showing completed and total variables?

I have a problem with my react code, when I put that I want the completed and total of the todocounter to be the variables, they are not displayed on the screen as they should, being 2 of 4 all completed. But if I remove the variables and put a number, it returns the numbers with no problem, so it’s not a z-index problem.

I don’t know what to do, I’m not an expert in react or anything, I’m a student

this is my app.js

import React from 'react';
import { TodoCounter } from './TodoCounter';
import { TodoSearch } from './TodoSearch';
import { TodoList } from './TodoList';
import { TodoItem } from './TodoItem';
import { CreateTodoButton } from './CreateTodoButton';
import { Bubbles } from './Bubbles';

const defaultTodos = [
  { text: 'Cortar cebolla', completed: true },
  { text: 'Tomar el curso de Intro a React.js', completed: false },
  { text: 'Llorar con la Llorona', completed: false },
  { text: 'LALALALA', completed: false },
];

function App() {
  const [todos, setTodos] = React.useState(defaultTodos);

  const [searchValue, setSearchValue] = React.useState('');

  const completedTodos = todos.filter(
    todo => !!todo.completed //devuelve un booleano
    ).lenght;
  
  const totalTodos = todos.lenght;

  const searchedTodos = todos.filter(
    (todo) => {
      const todoText = todo.text.toLowerCase();
      const searchText = searchValue.toLowerCase();
      
      return todoText.includes(searchText)
    }
  );
  
  console.log('Los usuarios buscan todos de ' + searchValue);

  return (
    <>
     <TodoCounter 
     completed={completedTodos}
     total={totalTodos} 
     />
     <TodoSearch 
     searchValue={searchValue}
     setSearchValue={setSearchValue}
     />

    <Bubbles />

    <TodoList>
      {searchedTodos.map(todo => ( //El metodo map crea un array a partir del array inicial
        <TodoItem 
        key={todo.text} 
        text={todo.text}
        completed={todo.completed}
        />
      ))} 
      {}
    </TodoList>

    <CreateTodoButton />
    
    </>
  );
}

export default App;

todocounter.js

import React from 'react';
import './styles/TodoCounter.css';

const TodoCounter = ({ completed, total }) => {
  return (
    <h1 className='todo-Title'>
      Has completado <span>{completed}</span> de <span>{total}</span> TODOs
    </h1>
  );
}

export { TodoCounter };

This is what it looks like if I use the variables.

enter image description here

And this is what it looks like if I just use numbers

enter image description here

I tried change the const for a number and it works, but i need that the app put the correct numbers of todos completed and total for complete.

Get Back VS Codes Inline Vertical Merge Editor

VS Code is now asking me to resolve conflicts in merge editor when I am opening some files. I want to use the old inline view where I can see the changes in a simple vertical style and choose what to accept or reject. However instead of showing me that it is not showing the errors and instead showing me this, which takes me to a 3 merge editor.

enter image description here

I do not want this and have turned it off in the settings as shown here
git merge conflict window off

However it is still showing me this and not giving me the old window. However for some files the old window will work for some reason. I want all my files on the old inline window with my accect incoming or accept current buttons. Can anyone help?

Javascript: How can export a PNG image with a black background and white brush from canvas?

Input:
An original image is uploaded then a canvas overlay with the size of the image and then brush painted on.

https://i.stack.imgur.com/7UKsG.png

Output:
Is the mask image, defining the areas that need to be removed

  • The mask image should be a PNG, and should have the same resolution as the original image
  • The mask should be black and white with no grey pixels

https://i.stack.imgur.com/7UKsG.png

its not a question this is my code for a game sooo anybody checked i am to bad in js but in my opinion is prety good :) [closed]

so yes, this is the game that I think was well done, I admit that I don’t know much about java script and I only do these from a practice point of view, but I would appreciate it if anyone could take a look and try it out and give me some tips on how I could improve. 🙂

html:

<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body onload="draw()">
    <style>
        td{
            width: 95px;
            height: 95px;
            background-color: aqua;
            text-align: center;
        }
        img
        {
            width: 50px;
            height: auto;
        }
    </style>
    <div style="background-color: bisque; height: 500px; width: 500px; margin-right: auto; margin-left: auto;">
        <table id="table">

        </table> 
    </div>
    
    <script src="script3.js"></script>
</body>
</html>

js:

var list = [];

function draw()
{
    list = [];
    let table = document.getElementById("table");
    let cells = 25;
    let text = "<tr>"

    for (let i = 0; i < cells; i++) 
    {
        list.push(0);
        if (i%5 == 0) {text += "<tr></tr>"}
        text += `<td onclick = "c(this)" id = "${i}"><img src = "vakondos feladat/Házi feladatok/turas.png"></td>`;
    }
    text += "</tr>"
    table.innerHTML = text;

    placed();
}

function c(object)
{
    console.log(list)
    if (list[object.id] == 1) {
        console.log("+1")
        document.getElementById(object.id).innerHTML = `<img src = "vakondos feladat/Házi feladatok/turas.png"></img>`;
        list[object.id] = 0;
    }
}

function placed()
{
    let placed = 0;

    while (placed < 10) {
        let rand = Math.floor((Math.random()*24));  
        
        if (list[rand] == 0) 
        {
            list[rand] = 1;
            placed++    
        }
        document.getElementById(rand).innerHTML = `<img src = "vakondos feladat/Házi feladatok/vakond.png"></img>`
    }

    console.log(placed);
    out();
}

function out()
{
    setInterval(() => {
        location.reload()
    }, 3300);
}

Need to make search and close SVG icons at the same position?

I need to make the search icon and the close SVG icon appear at same position but failed to achieve this !

My site: https://softcroco.com/

Screenshots:

enter image description here

enter image description here

So, is there any solution to get the search and close SVG icons at same position when the user click on it?

My Code:

#submitSearchButton {
}

#searchInput {
flex-grow: 1;
padding: 15px 145px;
border: none;
width: 100%;
height: 19%important;
font-family: 'Poppins';
font-size: 18px;
}

#searchForm {
width: 100%;
height: 75%!important;
position: relative;
display: unset;
}

.search-container {
display: flex;
position: absolute; /* Change this */
width: 100%; /* Add this */
top: 0; /* Add this */
left: 0; /* Add this */
}

#openSearchButton, #closeButton {
padding: 6px!important!;
border: none!important;
cursor: pointer!important;
position: absolute!important;
background-color: transparent!important;
color: white!important;
position: absolute!important; /* Change this */
top: 60%!important;
transform: translateY(-50%)!important;
right: 92px!important;
display: flex!important;
align-items: center!important;
}

#openSearchButton:hover { color: #cccccc!important; } #openSearchButton svg { transition: color 0.2s ease-in-out!important; }

#submitSearchButton {
position: relative;
cursor: pointer;
top: -38px;
right: -97px;
border: none;
background: none;
}
#openSearchButton svg {
width: 1em;
height: 1em;
}
#closeButton svg {
width: 2.5em;
height: 1em;
}

#closeButton {
display: none;
color: white;
right: 0; /* Add this */
}

<nav class="navbar">
  <div class="search-container" id="searchContainer" style="display: none;">
    <form id="searchForm" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="GET">
      <input type="text" placeholder="Search For Apps or Games..." name="s" id="searchInput">
      <button type="submit" id="submitSearchButton">
        <!-- SVG icon code -->
        <svg viewBox="0 0 512 512" fill="currentColor" aria-hidden="true" width="20" height="20"><path fill-rule="evenodd" clip-rule="evenodd" d="M208 48c-88.366 0-160 71.634-160 160s71.634 160 160 160 160-71.634 160-160S296.366 48 208 48zM0 208C0 93.125 93.125 0 208 0s208 93.125 208 208c0 48.741-16.765 93.566-44.843 129.024l133.826 134.018c9.366 9.379 9.355 24.575-.025 33.941-9.379 9.366-24.575 9.355-33.941-.025L337.238 370.987C301.747 399.167 256.839 416 208 416 93.125 416 0 322.875 0 208z"></path></svg>
      </button>
    </form>
<button type="button" id="closeButton">
  <!-- SVG icon code -->
  <svg viewBox="0 0 512 512" aria-hidden="true" width="1em" height="1em">
    <path d="M71.029 71.029c9.373-9.372 24.569-9.372 33.942 0L256 222.059l151.029-151.03c9.373-9.372 24.569-9.372 33.942 0 9.372 9.373 9.372 24.569 0 33.942L289.941 256l151.03 151.029c9.372 9.373 9.372 24.569 0 33.942-9.373 9.372-24.569 9.372-33.942 0L256 289.941l-151.029 151.03c-9.373 9.372-24.569 9.372-33.942 0-9.372-9.373-9.372-24.569 0-33.942L222.059 256 71.029 104.971c-9.372-9.373-9.372-24.569 0-33.942z" fill="black"></path>
  </svg>
</button>

  </div>
  <button type="button" id="openSearchButton">
    <!-- Add your search icon SVG code here -->
<svg viewBox="0 0 512 512" aria-hidden="true" width="1em" height="1em">
  <path fill="white" fill-rule="evenodd" clip-rule="evenodd" d="M208 48c-88.366 0-160 71.634-160 160s71.634 160 160 160 160-71.634 160-160S296.366 48 208 48zM0 208C0 93.125 93.125 0 208 0s208 93.125 208 208c0 48.741-16.765 93.566-44.843 129.024l133.826 134.018c9.366 9.379 9.355 24.575-.025 33.941-9.379 9.366-24.575 9.355-33.941-.025L337.238 370.987C301.747 399.167 256.839 416 208 416 93.125 416 0 322.875 0 208z"></path>
</svg>
  </button>
  <!-- Other navigation items -->
</nav>

<script>
document.getElementById('openSearchButton').addEventListener('click', function() {
  document.getElementById('searchContainer').style.display = 'flex';
  this.style.display = 'none';
  document.getElementById('closeButton').style.display = 'block';
});

document.getElementById('closeButton').addEventListener('click', function() {
  document.getElementById('searchContainer').style.display = 'none';
  this.style.display = 'none';
  document.getElementById('openSearchButton').style.display = 'block';
});

document.getElementById('searchForm').addEventListener('submit', function(e) {
  const searchInput = document.getElementById('searchInput');
  const searchQuery = searchInput.value.trim();
  
  if (searchQuery === '') {
    e.preventDefault(); // Prevent the form from submitting if the search query is empty
  }
});
</script>

A lot of CSS edits without benefits!

Return a variable from a function to be used in a different function?

I’d like to return the object id created for a guest based on my if statement below. I’m new-ish to javascript and can’t figure out how to do this from the MDN function docs so wondering if there’s a way to return a variable from the below function so it can be used in another function below

const guest = await Guest.findOne({ email: req.body.email, user: event.user._id }).populate('event');

if (!guest) {          // see if guest already exists
    const newGuest = new Guest(req.body);  // create new guest
    newGuest.user = event.user._id;
    newGuest.event = event._id;
    await newGuest.save(); // save new guest to guest model
    event.guests.push(newGuest);
    await event.save(); // save guest to event
} else {
    event.guests.push(guest);
    await event.save(); // 
}

Javascript guessing number game [closed]

Can someone please give me the code for a javascript game where you have 100 buttons, all with values between 1 and 100, and rhe point of the game is to click on button that is computer generated randomly. You have several guesses, and if you get it right, message appears that you guessed it right.
The final product should look like this:

My main problem is that i can’t make buttons.

Extracting text from Xpath using JavaScript

Looking for a way to extract the text from an Xpath using javascript.

Example:
Xpath: Sometext

Want to return the value: Sometext.

Tried something like this with no luck.

var x_path = ‘my_xpath’;
var result = document.evaluate(x_path,document, null, XPathResult.STRING_TYPE, null);
console.log(result);

Output is just {}.

AJAX FormData POST not working: Payload not delivered to PHP page

AJAX POST Payload doesnt deliver to PHP Page

Im trying to send a form when the button “agregar-carrito” gets clicked, creating the form structure inside the .js, and sending it in directed to a .php page named “carrito.php” with POST as REQUEST_METHOD, but the .php page doesnt seem to get the payload from the AJAX. From the page where the data is getting delivered seems to be delivering the data just fine, the payload is sent with the following General Headers data:

Request URL: http://localhost/HC/carrito.php
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:80
Referrer Policy: strict-origin-when-cross-origin

but on the other end, carrito.php doesnt seem to get sent anything. Without the echos handling the warnings, it results with the following error:

**PHP Warning:  Undefined array key "REQUEST_METHOD" in D:Program FilesxampphtdocsHCcarrito.php on line 3**

script.js

$(document).ready(function() {
  // Manejar el evento clic del botón "Agregar al carrito"
  $('#agregar-carrito').on('click', function(e) {
    // Obtener los datos del producto
    var cantidad = $('#cantidad').val();
    var nombreProducto = $('#nombre-producto').text();
    var idProducto = $('html').attr('id');
    var precioUnitarioTexto = $('#precio-unitario').text();
    precioUnitarioTexto = precioUnitarioTexto.replace(' MXN', '');
    precioUnitarioTexto = precioUnitarioTexto.replace('Precio: $', '');
    var precioUnitario = parseFloat(precioUnitarioTexto);
    var imagenProducto = $('#imagen-producto').attr('src');

    // Calcular el precio total
    var precioTotal = cantidad * precioUnitario;

    // Crear un objeto FormData para enviar los datos del producto (incluyendo la imagen)
    var formData = new FormData();
    formData.append('cantidad', cantidad);
    formData.append('nombre', nombreProducto);
    formData.append('id', idProducto);
    formData.append('imagen', imagenProducto);
    formData.append('precioUnitario', precioUnitario);
    formData.append('precioTotal', precioTotal);

    // Enviar los datos del producto al archivo carrito.php utilizando AJAX
    $.ajax({
      url: 'carrito.php',
      method: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(response) {
        // Manejar la respuesta del servidor (si es necesario)
        console.log(response);
      },
      error: function(xhr, status, error) {
        // Manejar errores de la solicitud AJAX (si es necesario)
        console.error(error);
      }
    });
  });
});

carrito.php

<?php

if ($_SERVER["REQUEST_METHOD"] == 'POST') {
    $cantidad = $_POST['cantidad'];
    $nombre = $_POST['nombre'];
    $id = $_POST['id'];
    $imagen = $_POST['imagen'];
    $precioUnitario = $_POST['precioUnitario'];
    $precioTotal = $_POST['precioTotal'];

    // Realiza cualquier operación adicional con los datos recibidos

    // Ejemplo: Imprime los datos recibidos
    echo "Cantidad: $cantidad, Nombre: $nombre, ID: $id, Imagen: $imagen, Precio Unitario: $precioUnitario, Precio Total: $precioTotal";
} else {
    echo "Método de solicitud incorrecto.";
}
?>

Javascript Object Exists, but variables get Error Invalid data structure

The following javascript code works, but for some reason line 3 doesnt work as it gives me the below error. Line 2 with just console log data works and displays below. If data is valid, but why doesnt “nid” exist?

Error: Invalid data structure or nid value is missing.

{"nid":[{"value":283}],"uuid":[{"value":"4fb99a46-1383-4f0d-8c51-2743b55defea"}],"vid":[{"value":430}]}

enter image description here

Creating a Next.js app in VS Code does not have ‘Pages’ or ‘Styles’ folder

When creating a Next.js app in VS Code, I run the following command: ‘npx create-next-app@latest’ and go through the process of creating the app. However, Next.js’s website shows that I should have a ‘pages’ and ‘styles’ folder along with the ‘app’ and ‘public’ folder. I am unsure if this has to do with the ‘Would you like to use…’ section when creating the app if I am selecting the wrong options or what.

‘Would you like to use…’ section
Top level files and folders I am seeing

I updated Node.js and recreated the application multiple times using different selections in the ‘Would you like to use…’ section. I was hoping the folders would appear, but no success. I am unsure where to go here as I am new to using Next.js.

Show/hide field with jQuery

Is it possible to hide the ‘Please specify…’ field when I click ‘No’ after clicking ‘Yes’?

$(document).ready(function() {
        var policeInvolvedYes = $('input[name="policeInvolved"][value="yes"]');
        var policeDetailsGroup = $('#policeDetailsGroup');
        var policeDetails = $('#policeDetails');

        function updatePoliceDetailsField() {
            if (policeInvolvedYes.is(':checked')) {
                policeDetailsGroup.show();
                policeDetails.prop('required', true);
            } else {
                policeDetailsGroup.hide();
                policeDetails.prop('required', false);
            }
        }

        policeInvolvedYes.on('change', updatePoliceDetailsField);
        updatePoliceDetailsField();
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="form-group">
        <label>Were Police/Emergency Services involved?</label>
        <div class="radio">
          <label>
            <input type="radio" name="policeInvolved" value="yes"> Yes
          </label>
        </div>
        <div class="radio">
          <label>
            <input type="radio" name="policeInvolved" value="no"> No
          </label>
        </div>
      </div>

        <div id="policeDetailsGroup" style="display: none;">
            <label for="policeDetails">If yes, please specify:</label>
            <input type="text" class="form-control" id="policeDetails" name="policeDetails" placeholder="Enter details">
        </div>

Why is my timer (JS) not showing up/working?

Can anybody explain why my timer made with JavaScript is not showing up?
I don’t know if its a problem with the HTML or the JS code. It might even be the CSS code but I don’t think so.

window.onload = function() {
  var streamTimes = [{
      day: 1,
      hour: 19,
      minute: 0
    }, // Montag 19:00
    {
      day: 2,
      hour: 19,
      minute: 0
    }, // Dienstag 19:00
    {
      day: 3,
      hour: 19,
      minute: 0
    }, // Mittwoch 19:00
    {
      day: 4,
      hour: 19,
      minute: 0
    }, // Donnerstag 19:00
    {
      day: 5,
      hour: 20,
      minute: 0
    }, // Freitag 20:00
    {
      day: 6,
      hour: 15,
      minute: 0
    } // Samstag 15:00
  ];

  var countdownElement = document.getElementById("countdown");

  function updateCountdown() {
    var now = new Date();
    var nextStream;

    // Find next streams date
    for (var i = 0; i < streamTimes.length; i++) {
      var streamDate = getNextStreamDate(streamTimes[i].day, streamTimes[i].hour, streamTimes[i].minute);
      if (streamDate > now) {
        nextStream = streamDate;
        break;
      }
    }

    var distance = nextStream - now;

    // Timer "currently live" (If date is reached text is being shown for two hours)
    if (distance <= 0 && distance >= -7200000) {
      countdownElement.innerHTML = '<a href="https://twitch.tv/chyyyp">Stream momentan Live</a>';
      return;
    }

    // Calculation of Days, hours, minutes and seconds until next stream 
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Cooldown being shown here
    countdownElement.innerHTML = "Nächster Stream in: " + days + " Tage " + hours + " Stunden " + minutes + " Minuten " + seconds + " Sekunden";

    // Counting Seconds
    setTimeout(updateCountdown, 1000);
  }

  function getNextStreamDate(day, hour, minute) {
    var date = new Date();
    var daysToAdd = (day - 1 + 7 - date.getDay()) % 7;
    date.setDate(date.getDate() + daysToAdd);
    date.setHours(hour);
    date.setMinutes(minute);
    date.setSeconds(0);
    date.setMilliseconds(0);
    return date;
  }

  updateCountdown();
};
/* global */

body {
  font-family: 'Varela Round', Arial, sans-serif;
  background-color: #111;
  color: #fff;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  text-align: center;
}

h1,
h2 {
  margin-bottom: 1em;
}

p {
  margin-bottom: 0.5em;
}


/* header */

header {
  background-color: #222;
  padding: 20px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

h1 {
  font-size: 24px;
  margin: 0;
}


/* main */

main {
  padding: 20px;
  max-width: 600px;
}

section {
  margin-bottom: 2em;
  padding-top: 20px;
  transition: transform 0.3s ease;
}

section:first-child {
  padding-top: 0;
}

h2 {
  font-size: 20px;
}


/* divider */

.divider {
  border-top: 1px solid #fff;
  margin-bottom: -1em;
  /* Geändert von 1em zu -1em */
}


/* Hover-effect */

section:hover {
  transform: scale(1.1);
}

section:not(:hover) {
  opacity: 0.6;
}

section:not(:hover) h2,
section:not(:hover) p {
  transform: scale(0.9);
}

@media screen and (max-width: 600px) {
  h1 {
    font-size: 20px;
  }
}
<link href="https://fonts.googleapis.com/css2?family=Varela+Round&display=swap" rel="stylesheet">

<header>
  <h1>Der Streamplan</h1>
</header>

<main>
  <div class="divider"></div>
  <section>
    <h2>Montag</h2>
    <p>19:00 - 21:00 Uhr</p>
  </section>
  <div class="divider"></div>
  <section>
    <h2>Dienstag</h2>
    <p>19:00 - 21:00 Uhr</p>
  </section>
  <div class="divider"></div>
  <section>
    <h2>Mittwoch</h2>
    <p>19:00 - 21:00 Uhr</p>
  </section>
  <div class="divider"></div>
  <section>
    <h2>Donnerstag</h2>
    <p>19:00 - 21:00 Uhr</p>
  </section>
  <div class="divider"></div>
  <section>
    <h2>Freitag</h2>
    <p>20:00 - 24:00 Uhr</p>
  </section>
  <div class="divider"></div>
  <section>
    <h2>Samstag</h2>
    <p>15:00 - 18:00 Uhr</p>
  </section>
  <div class="divider"></div>
  <section>
    <h2>Sonntag</h2>
    <p>Kein Stream</p>
  </section>
  <div class="divider"></div>
</main>

WebGL not displaying my triangle despite no errors or warnings

WebGL not even rendering my triangle that I want its not giving me any errors or anything..

I’ve tried changing the order of how I do the inputs and rewriting the shader code multiple times.
I’m just trying to draw a triangle.

Here are some snippets of the code I am using

My Vertex Shader

    attribute vec4 a_position;
    attribute vec4 a_color;
    varying vec4 v_color;

    void main()
    {
        v_color = a_color;
        gl_Position = a_position;
    }

My Fragment Shader

    attribute vec4 a_position;
    attribute vec4 a_color;
    varying vec4 v_color;

    void main()
    {
        v_color = a_color;
        gl_Position = a_position;
    }

the Draw function

function drawTri(x1,y1,x2,y2,x3,y3){
    const a_position = new Float32Array([x1,y1,0,1,x2,y2,0,1,x3,y3,0,1]);

    const a_color = new Float32Array([
      testColor[0],testColor[1],testColor[2],testColor[3],
      testColor[0],testColor[1],testColor[2],testColor[3],
      testColor[0],testColor[1],testColor[2],testColor[3]
    ]);

    gl.useProgram(myShaders.untextured.ProgramInf.program);
    gl.viewport(0, 0, 630, 360);

    //? Bind Positional Data
    gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);

    gl.bufferData(gl.ARRAY_BUFFER, a_position, gl.STATIC_DRAW);

    gl.enableVertexAttribArray(a_position_Location);

    gl.vertexAttribPointer(a_position_Location, 4, gl.FLOAT, false, 0, 0);

    //? Bind Color Data
    gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);

    gl.bufferData(gl.ARRAY_BUFFER, a_color, gl.STATIC_DRAW);

    gl.enableVertexAttribArray(a_color_Location);

    gl.vertexAttribPointer(a_color_Location, 4, gl.FLOAT, false, 0, 0);

    gl.drawArrays(gl.TRIANGLES, 0, 3);
}

testColor is defined as

const testColor = [0,0,1,1];

For…of loop only returning last HTML element [duplicate]

I am trying to set event listeners for a list of HTML elements. The main code that does this is below:

let pageIds = ['functions', 'lists', 'forLoops', 'lambda', 'maps'];
let pageLinks = document.getElementsByClassName('link');

    for (var l of pageLinks) {
        console.log(l.id)
        l.addEventListener('click', () => {
            console.log(l.id + ' was clicked');
            for (var x in pageIds) {
                document.getElementById(pageIds[x] + '-div').classList.remove('show');
            }
            document.getElementById(`${l.id}-div`).classList.add('show');
        })
    }

When using the for keyword, this loop should iterate through each element individually, and thus set an event listener for each element individually.

However, when I run this code, the eventlistener function does not work as it should.

When the page loads, the console properly outputs the following:

functions
lists
forLoops
lambda
maps

The issue happens when I then go and try to click on one of the links. The event listener only ever outputs the maps id, and nothing else. I don’t understand why this would be happening since the first console.log() proved that things were reading properly, but then it broke by the time it got into the eventlistener code. Each time the loop runs, l is a different HTML element, and thus should not overwrite the one before it.

Is there something in my code that I am missing?