undefined Parameter in Javascript

The following JS-Code enables a Demo-Drum-Kit:

var numberOfdrumButtons = document.querySelectorAll(".drum").length;
// call 2 functions when the click-event is triggered
for (var i = 0; i < numberOfdrumButtons; i++) {
    document.querySelectorAll(".drum")[i].addEventListener("click", function (){

    var buttonInnerHTML = this.innerHTML;

    makeSound(buttonInnerHTML);
    buttonAnimation(buttonInnerHTML);    

    });
}
// call 2 functions when the keydown-event is triggered
document.addEventListener("keydown", function(event){

    makeSound(event.key);
    buttonAnimation(event.key);    

  
});
//function to make sound
function makeSound(key){

    switch (key) {
        case "w":
            var audio = new Audio("sounds/crash.mp3");
            audio.play();
        case "a":
            var audio = new Audio("sounds/kick-bass.mp3");
            audio.play();
        case "s":
            var audio = new Audio("sounds/snare.mp3");
            audio.play();
        case "d":
            var audio = new Audio("sounds/tom-1.mp3");
            audio.play();
        case "j":
            var audio = new Audio("sounds/tom-2.mp3");
            audio.play();
        case "k":
            var audio = new Audio("sounds/tom-3.mp3");
            audio.play();
        case "l":
            var audio = new Audio("sounds/tom-4.mp3");
            audio.play();
        
            
            break;
       
        default:
            break;

       }

    }
//function to add an animation
function buttonAnimation(currentKey){

    var activeButton = document.querySelector("." + currentKey);
    activeButton.classList.add("pressed");
    setTimeout(function() {
        activeButton.classList.remove("pressed");
    }, 100
    
    )

}

So my Question is about the currentKey-Parameter in the function buttonAnimation. Where does it come from? How can it function if its not defined before? How does it work? I stumpled across the same kind of value in another JS-Exercise and i have no clue. There the Parameter is called currentColor.

Thx in advance!

I tried to event instead, but the function buttonAnimation(currentKey) doesnt work. To be specific the setTimeout-function didnt work then.

The function I made for my dropdown menu is working but not 100%

I have created a drop down menu with custom radio buttons on the menu, some of the buttons label have images and some do not have. I create a function the when a radio button is selected its label will be display on the dropdown wrapper with its image. It works with the radio buttons with images on the label but not on the ones without.

here is the code.

<div id="dropdown-wrapper" class="dropdown-wrapper" tabindex="1">
            <span>View Additional Shipping Options or Select a Carrier</span>
            <ul class="dropdown-list">
               <li>
                  <div class="radio-group">
                     <label class="custom-radio">
                     <input type="radio" name="option" value="">
                     <span class="radio-dot"></span>
                     <span class="custom-radio-label">$2.99 - Free or Standard Shipping</span>
                     </label>
                  </div>
                  <div class="radio-group">
                     <label class="custom-radio">
                     <input type="radio" name="option" value="">
                     <span class="radio-dot"></span>
                     <span class="custom-radio-label">$14.99 - Expedited Shipping</span>
                     </label>
                  </div>
                  <div class="radio-group">
                     <label class="custom-radio">
                     <input type="radio" name="option" value="">
                     <span class="radio-dot"></span>
                     <span class="custom-radio-label">$34.99 - International Shipping</span>
                     </label>
                  </div>           
               </li>
               <li>
                  <p>Best Discounted Delivery Options to your Destination</p>
                  <div class="radio-group">
                     <label class="custom-radio">
                     <input type="radio" name="option" value="">
                     <span class="radio-dot"></span>
                     <span class="custom-radio-label"><span><img src="https://placehold.co/22x18" alt=""></span>$8.89 - UPS SurePost 'Saver' (Typical Delivery: 5-8 Days to 78738)</span>
                     </label>
                  </div>
                  <div class="radio-group">
                     <label class="custom-radio">
                     <input type="radio" name="option" value="">
                     <span class="radio-dot"></span>
                     <span class="custom-radio-label"><span><img src="https://placehold.co/22x18" alt=""></span>$15.85 - UPS Ground Service (Typical Delivery: 3 Days to 78738)</span>
                     </label>
                  </div>
                  <div class="radio-group">
                     <label class="custom-radio">
                     <input type="radio" name="option" value="">
                     <span class="radio-dot"></span>
                     <span class="custom-radio-label"><span><img src="https://placehold.co/22x18" alt=""></span>$15.95 - UPS 2 Day Delivery</span>
                     </label>
                  </div>           
                  <div class="radio-group">
                     <label class="custom-radio">
                     <input type="radio" name="option" value="">
                     <span class="radio-dot"></span>
                     <span class="custom-radio-label"><span><img src="https://placehold.co/22x18" alt=""></span>$36.99 - UPS Nex Day Air</span>
                     </label>
                  </div>           
               </li>
               <li>
                  <p>Ground Options (Delivery Typically 7 business days or less after order ships)</p>
                  <div class="radio-group">
                     <label class="custom-radio">
                     <input type="radio" name="option" value="">
                     <span class="radio-dot"></span>
                     <span class="custom-radio-label"><span><img src="https://placehold.co/22x18" alt=""></span>$36.68 - FedEx Home Delivery (Typical Delivery: 3-4 Days to 78738)</span>
                     </label>
                  </div>
               </li>
            </ul>
         </div>
document.addEventListener('DOMContentLoaded', function() {
    const dropdownWrapper = document.getElementById('dropdown-wrapper');
    const radioButtons = dropdownWrapper.querySelectorAll('.dropdown-list input[type="radio"]');
    const spanElement = dropdownWrapper.querySelector('span');

    function handleRadioButtonSelection(event) {
        const selectedRadioButton = event.target;
        console.log(selectedRadioButton);
        if (selectedRadioButton.checked) {
            const nextSibling = selectedRadioButton.querySelector('.custom-radio-label');
            const labelElement = nextSibling.nextElementSibling;
            const label = labelElement ? labelElement.textContent : null;
            const imageSrc = labelElement ? labelElement.querySelector('img').src : null;
            spanElement.innerHTML = `${imageSrc ? `<img src="${imageSrc}" alt="">` : ''} ${label ? label.trim() : ''}`;
        }
    }


    // Adding event listeners to the radio buttons
    radioButtons.forEach(radioButton => {
        radioButton.addEventListener('change', handleRadioButtonSelection);
    });
});

I want it to work even on the labels without images.

how to make a dinamic grid with JavaScript?

I am new to javascript, and I’m trying to create a grid of 5 by 5 blocks dinamically and each one has to have a unique ID.

I tried to create a 5×5 grid of blocks dynamically in JavaScript and assign each block a unique ID. I was expecting each block to be displayed on the page and have a unique ID, but I don’t see the blocks on the page. I’m not sure what I’m doing wrong

function createGrid() {
    let grid = document.createElement('div');
    grid.style.display = 'grid';
    grid.style.gridTemplateColumns = 'repeat(5, 1fr)';
    grid.style.gridTemplateRows = 'repeat(5, 1fr)';

    for(let i = 0; i < 25; i++) {
        let block = document.createElement('div');
        block.id = 'block' + i;
        grid.appendChild(block);
    }

    document.body.appendChild(grid);
}

createGrid();

Previewing PDF inside MUI tooltip

I am trying to display a preview of a PDF inside an MUI Tooltip whenever someone hovers over an MUI ListItem. I am able to display PNGs and JPGs as previews inside the tooltip using Next.js’ Image component, but when I tried using @react-pdf/renderer to show PDFs, I am only able to display the viewing area of the PDF, but not the PDF itself. My best guess is one of the following: 1) Could it be the URL is not being recognized properly 2) could it be that the PDF is not being saved properly when it’s initially uploaded, so there’s nothing to display from the URL, 3) It’s trying to show the PDF too quickly, so it’s not loaded in properly from where it’s saved? Below is a minimum reproducible example:

const Dropzone = (props) => {
  const { files, setFiles } = props

  const onDrop = useCallback(acceptedFiles => {
    if (acceptedFiles?.length) {
      setFiles(prev => ([
        ...prev,
        ...acceptedFiles.map(file => (
          Object.assign(file, { preview: URL.createObjectURL(file) })
        ))
      ]))
    }
  }, [])

  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop })

  return (
      <List>
        {files.map((file, index) => (
            <Tooltip
              TransitionComponent={Zoom}
              title={
                <PDFViewer>
                   <Document
                     file={file.preview}
                   >
                      <Page pageNumber={1}/>
                  </PDFViewr>
              }
            >
              <ListItem key={file.name}>
                <ListItemAvatar>
                  <DescriptionIcon />
                </ListItemAvatar>
                <ListItemText
                  primary={file.name}
                  secondary={file.size}
                />
              </ListItem>
            </Tooltip>
        ))}
      </List>

  )
}

export default Dropzone

Chrome refuses to use HTTP/2 for fetch upload while using streams

Currently trying to create a simple file upload application, I’m using S3 as the storage and presigned-url to do the upload from the client-side.

The application is built using SvelteKit and using Fetch for uploading.

const duplex = { duplex: 'half' };

const response = await fetch(url, {
  method: 'POST',
  body: file.stream(),
  headers: {
  'Content-Type': file.type
  },
  signal: this.abortController?.signal,
  ...duplex
});

When running the app in Firefox, it uploads normally, when attempting to run it on chrome, it gets interrupted with the Quic/Http/2 error net::ERR_H2_OR_QUIC_REQUIRED

Both were running on localhost with Http. I assumed that chrome had some extra protections against running this type of upload through a non SSL channel, so I tried to deploy the app and run it over HTTPS, still it worked on firefox and not on chrome.

how to realize header-method steps in vuetify?

I understand, that i able to use items property, but i wanna use v-stepper-header with v-stepper-window. I try to start code from official examples and take the white screen as a result. How to fix this code, to take normal step-system?

<template>
  <v-container>
    <v-stepper v-model="e1">
      <template v-slot:default="{ prev, next }">
      <v-stepper-header>
        <v-stepper-item title="Job Search" :complete="e1 > 1" value="1"></v-stepper-item>
        <v-divider></v-divider>
        <v-stepper-item title="Job Search" :complete="e1 > 2" value="2"></v-stepper-item>
        <v-divider></v-divider>
        <v-stepper-item title="Job Search" :complete="e1 > 3" value="3"></v-stepper-item>
      </v-stepper-header>

      <v-stepper-window>

        <v-stepper-window-item step="1">
          <v-text-field v-model="user.firstName" label="First Name"></v-text-field>
          <v-text-field v-model="user.lastName" label="Last Name"></v-text-field>
          <v-text-field v-model="user.email" label="Email"></v-text-field>
        </v-stepper-window-item>

        <v-stepper-window-item step="2">
          <v-text-field v-model="user.occupation" label="Occupation"></v-text-field>
          <v-text-field v-model="user.city" label="City"></v-text-field>
          <v-textarea v-model="user.bio" label="Bio"></v-textarea>
        </v-stepper-window-item>

        <v-stepper-window-item step="3">
          <div>First Name: {{ user.firstName }}</div>
          <div>Last Name: {{ user.lastName }}</div>
          <div>Email: {{ user.email }}</div>
          <div>Occupation: {{ user.occupation }}</div>
          <div>City: {{ user.city }}</div>
          <div>Bio: {{ user.bio }}</div>
        </v-stepper-window-item>

      </v-stepper-window>
      </template>
    </v-stepper>
  </v-container>
</template>

<script>
export default {
  data() {
    return {
      e1: 1,
      items: [
          'User information',
          'Personal details',
          'Confirmation',
          'Greetings',
      ],
      user: {
        firstName: '',
        lastName: '',
        email: '',
        occupation: '',
        city: '',
        bio: '',
      },
    };
  },
  methods: {
    submitForm() {
      // Обработка отправки формы
      console.log("Submitted", this.user);
      this.e1 = 1; // Reset the form or move to a 'thank you' step
    },
  },
};
</script>


<style>
  .v-sheet {
    width: 650px;
    margin: auto;
  }
</style>

enter image description here

I checked all the issues and any stackoverflow pages, but no code works in my project.

Instagram browser not showing mobile website correctly

I am struggling with the instagram browser. I made a wordpress website, which is working fine on any browser except instagram. The problem here is that the javascript code is not loading.

Is there some kind of fix to ensure instagram to load all my scripts? Or else is there way to always open the link in the instagram profile in an external browser instead?

Any help is appreciated.

I tried to defer my script but that did not fix it.

Simple CSS JavaScript doesn’t work in safari

This code creates 10 circles that move left or right/up and down the width and height of the webpage:

const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);

for (let i = 0; i < 10; i++) {
  const shape = document.createElement('div');
  shape.classList.add('shape');
  shape.style.top = `${Math.random() * (vh - 50)}px`;
  shape.style.left = `${Math.random() * (vw - 50)}px`;
  shape.style.backgroundColor = getRandomColor();
  document.body.appendChild(shape);
}

function getRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

const shapes = document.querySelectorAll('.shape');

shapes.forEach((shape, index) => {
  // Randomize animation duration for each shape
  const duration = Math.random() * (8 - 3) + 3; // Random value between 3 and 8 seconds
  shape.style.animationDuration = `${duration}s`;

  // Randomize animation delay for each shape to prevent synchronization
  const delay = Math.random() * (index * 0.5);
  shape.style.animationDelay = `-${delay}s`;

  // Assign random animation direction (X or Y)
  const direction = Math.random() < 0.5 ? 'moveX' : 'moveY';
  shape.style.animationName = direction;
});
body {
  font-family: sans-serif;
  color: #000000;
  /* Black */
  text-align: center;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  overflow: hidden;
}

.shape {
  position: absolute;
  opacity: 0.6;
  mix-blend-mode: overlay;
  animation-duration: 5s;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
}

@-webkit-keyframes moveX {
  0% {
    left: 0;
  }
  50% {
    left: calc(100vw - 50px);
  }
  100% {
    left: 0;
  }
}

@-webkit-keyframes moveY {
  0% {
    top: 0;
  }
  50% {
    top: calc(100vh - 50px);
  }
  100% {
    top: 0;
  }
}


/* Adjust shape size */

.shape {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

  <title>Animated Shapes</title>
</head>

<body>
</body>

</html>

It creates the shapes and runs fine on all browsers except safari.

Anyone know why this is? Here is the website where the code runs.

I tried to run the website on my iPad and iPhone on safari. I expected the shapes to show up just fine like on all other browsers, but instead I was met with a blank white screen.

Understanding the Use of addEventListener and querySelector and Number() in JavaScript

I’m working through some JavaScript exercises and came across a code snippet involving event listeners and input value processing. Despite researching and experimenting with the code, I’m still unclear about certain aspects. The code snippet is as follows:

document.querySelector('.check').addEventListener('click', function () {
const guess = Number(document.querySelector('.guess').value);
console.log(guess,typeof guess)

My understanding is limited to recognizing that document.querySelector(‘.check’) selects the first element with the class check, and .addEventListener(‘click’, function () {…}) attaches a click event listener to this element. However, I’m struggling to fully grasp the following

Check if object is in array, if not push it in [duplicate]

I have an problem. I have an empty array, on click I want to create an object, check if this object is in array, if not I want to add it to an array. Problem is that multiple same objects are added at one click. I would appreciate if someone help me fixing this code..

function addToList (list, item) {
    if(list.length === 0) {
        list.push(item);
    } else {
        list.forEach(el => {
            if(el.title === item.title){
                return
            } else{
                list.push(item)}
    })}
}

Can someone explain [closed]

I am right now doing freeCodeCamp course in JavaScript and I can’t solve one problem, can someone help me?

Dont ask why it is so many else if statemens

When price is 19.5, the value in the #cash element is 20, cid is [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]], and the #purchase-btn element is clicked, the value in the #change-due element should be Status: INSUFFICIENT_FUNDS

let price = 19.5; // set the price of the item
let cid = [
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],
  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100]
];

const cashInput = document.getElementById("cash");
const changeDiv = document.getElementById("change-due")
const btn = document.getElementById("purchase-btn");

btn.addEventListener("click",()=>{
  let cash = parseFloat(cashInput.value);
  if(cash < price){
    alert ("Customer does not have enough money to purchase the item")
  } else if(cash === price){
  changeDiv.textContent ="No change due - customer paid with exact cash"
  } else if(price === 19.5 || cash === 20){
    changeDiv.textContent = "Status: OPEN QUARTER: $0.5"
  } else if(price === 3.26 || cash === 100){
    changeDiv.textContent ="Status: OPEN TWENTY: $60 TEN: $20 FIVE: $15 ONE: $1 QUARTER: $0.5 DIME: $0.2 PENNY: $0.04"
  } else if (price === 19.5 || cash === 20 || JSON.stringify(cid) === JSON.stringify([["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])) {
    changeDiv.textContent = "Status: INSUFFICIENT_FUNDS";
  }
})
Cash: <input id="cash"><br>
Change due: <span id="change-due"></span><br>
<button id="purchase-btn">Purchase</button>

Vertically aligning content across two different (parallel) columns using CSS

I’m using CSS grid layout, and would like to vertically align images in the left column to associated text in the right column. Is there a way to do that using CSS (without JavaScript)?

There are many posts about aligning content in the same column, which is not what I need. I need to align it across two different columns.

Example:

<div class="container">
<div class="left-col">
<img src="1.png" class="p1"/>
<img src="2.png" class="p2"/>
<img src="3.png" class="p2"/>
</div>
<div class="right-col">
<p class="p1">Lorem ipsum...</p>
<p class="p2">Lorem ipsum...</p>
<p class="p3">Lorem ipsum...</p>
</div>
</div>

I want to align each img.pN with the corresponding p.pN.

I’m using vanilla HTML and CSS, not Bootstrap. I’d rather avoid Javascript but can use it if necessary. I can’t use any external libraries beyond that, though.


As requested, here is the column CSS:

I started with a simple grid CSS, but can switch to anything which gives me the desired result:

div.container {
    display: grid;
    grid-template-columns: 1fr 1fr;
}

If a flex layout would be better, I’m open to that.

Importing A Library To Project

I am trying to, pardon my wording as this is my first time trying to import a library to a personal project, import the library package mathjs.

(https://mathjs.org/docs/getting_started.html).

However I keep getting the error on my site “math is undefined” when I go to use it.

See photo of the error in console log here

// Example in my JavaScript of me attempting to access this library:
math.evaluate('12 / (2.3 + 0.7)');

This is my first time attempting anything like this. I must be missing a step.
What step am I missing?

Steps I took/have taken include:

  1. Ran NPM install

npm install mathjs –save

  1. Checked package.json and the new dependency is there:
  "dependencies": {
    "mathjs": "^12.4.0"
  }
  1. These two (tested separately) give the original error “math is undefined.”

<script src="math.js" type="text/javascript"></script>

<script src="math.min.js" type="text/javascript"></script>

  1. But replacing those with require gave a separate, fatal error:

const math = require('mathjs');

Fatal error: Constant expression contains invalid operations in C:xampphtdocsGroceryListGeneratorPagesindex.php on line 3

React/JavaScript importing code across domains at run time

I have a scenario where i have 2x React applications built with Vite. One is a library and one is a traditional core React application. I am able to create code in the library, publish it as a js file and then link and import during build time. At the moment, my library is bundling each component as a standalone JS file so importing them on their own works great. However, i have a scenario where i want to dynamically import something during run time (so in a live environment, not during build). I would like it so i can continue to push new JS components under a different domain, and then dynamically reference them on the core application. For example

CORE Application running under domain: https://sometestdomain.com

    const getRoute = () => {
        // DO LOGIC HERE TO DATABASE LOOK UP A ROUTE, FOR NOW I WILL MOCK IT
        return 'http://127.0.0.1:4173/components/profilepage.js'
    }
    const ProfilePage = React.lazy(() => import(getRoute()));

What i need is, the domain/cdn thats housing this individual JS components can continue to add as many as they want. I can then build some sort of ‘loader’ component in the core ui that can grab this .js from any domain and run it. Both packages are built from me so it would never end up in a scenario where one of the .js files loaded into the core app couldn’t work or something.

I’ve looked at something like vite-federation but this would only resolve it during build time and if i know a full list of the imports i want to do (which i don’t). Ive also just simply tried to put the .js files behind an API and make API calls to them but then im noticing the javascript is not executable at this point so just renders plain text.

Any suggestions would be amazing, thank you