Firing a button when its container is about to be hidden

I’m building a simple menu with a collection of buttons. The first button toggles a class which is use show or hide the following div full of more buttons. That part works.

The tricky part is closing the menu when I click out. From various questions around SO, I get the solution of doing the following:

  • Set the tabindex on the menu container.
  • Set the focus on the menu container when the menu is opened.
  • use onblur to toggle off the class which opens the menu.

That part also works, but the buttons no longer work.

I’m guessing that the onblur happens first, and that closing the menu prevents the button from firing. If I disable the class toggle, then the button will fire.

I have tried using onclick as well as addEventListener with both true an false. Nothing helps.

Any suggestions on how I can get the button to fire before the menu closes?

let menu = document.querySelector('div#menu');
menu.setAttribute('tabindex',1);

let toggle = menu.querySelector('button#toggle');
toggle.onclick = event => {
  toggle.classList.toggle('open');
  menu.focus();
};

menu.querySelector('button#apple').onclick = event => {
  console.log('apple');
};
menu.querySelector('button#banana').addEventListener('click', event => {
    console.log('banana');
}, false);
menu.querySelector('button#cherry').addEventListener('click', event => {
    console.log('cherry');
}, true);

//  hide when clicked off
    menu.onblur = event => {
      console.log('byebye');
      toggle.classList.toggle('open', false);
    };
div#menu {
  position: relative;
  button#toggle+div {
    position: absolute;
    display: none;
    flex-direction: column;
  }
  
  button#toggle.open+div {
    display: flex;
  }
}
<div id="menu">
  <button id="toggle">Things</button>
  <div>
    <button id="apple">Apple</button>
    <button id="banana">Banana</button>
    <button id="cherry">Cherry</button>
  </div>
</div>
<p>Some stuff</p>

How to convert cubemap to equirectangular projection JavaScript

I need to convert these six separate cubemap tiles to an equirectangular projection. I’m not familiar with THREE or anything, I just want to use these images with photo-sphere-viewer.

    function convert(bubbliURL) {
  const bubbliId = new URL(bubbliURL).pathname.replaceAll("/", ""),
        directions = ["nx", "ny", "nz", "px", "py", "pz"];

      for (const direction of directions) {
        const image = new Image;
        image.onload = () => document.body.append(image);
        image.src = `https://d39cwcjmzdw2iw.cloudfront.net/${bubbliId}/stitched_${direction}.jpg`;
  }
}

convert("http://on.bubb.li/561309a7zrtjetjc40ojhie");
img { width: 40%; }

How to remove material from STL file? [closed]

CLICK HERE FOR PICTURE OF EXPECTED OUTCOME

CLICK HERE FOR A PREVIEW OF RED CYLINDER TOOL BIT

https://codepen.io/Maximusssssu/pen/dPGyrrP?editors=1000

https://drive.google.com/file/d/1knlg1YN5MFQIG8uY8YmnXAPHmysvKQ-Y/view?usp=sharing

Dear readers, I have created an interactive webpage where users can upload an STL file and also move a red cylinder created at the origin in the 3d dimension (+X,-X ,+Y,-Y,+Z,-Z) . For simplicity, assume that the red cylinder is a mill bit or basically a circular knife that can cut through anything. When the user move the red cylinder into or on the surface of the STL solid, how do i create the visualization of cutting as seen in the picture of my expected outcome above.

I have provided all the necessary files including the STL model that can be downloded for testing.

  function createHole() {
    // TODO: Students should implement the cut creation functionality here
    // Hint: You'll need to:
    // 1. Check if clickedPoint and stlMesh exist
    // 2. Create a cylinder geometry for the cut
    // 3. Position it at the clicked point
    // 4. Use CSG operations to subtract the cylinder from the STL mesh
    // 5. Update the scene with the new mesh
    
    alert('CREATE CUT function needs to be implemented!');
  }

work post survey super easy and fun 5 questions

NEED DATA FOR PROJECT PLEASE ANYTHING HELPS

I WANT DATA AND I NEED DATA

https://docs.google.com/forms/d/e/1FAIpQLScvX8uACIg7zqUQ8vXpFxg6WIWZhjXmIP8tMVagS7_IBnza_Q/viewform

THIS IS FOR A GRADE ITS STRAIGHT TO THE POINT, 5 EASY QUESTIONS,
DID I MENTION ITS A PROJECT THATS FOR A GRADE. ITS ABOUT WORK I KNOW WORK SUCKS BUT PLEASE FILL IT OUT ANYTHING HELPS I NEED ATLEAST 2000 RESPONSES TO GET ACCURATE DATA
NO IM NOT A BOT NO IM NOT AN AI YES YOU WILL FEEL GOOD ABOUT YOURSELF HELPING ME

How to remove material from STL file?

CLICK HERE FOR PICTURE OF EXPECTED OUTCOME

CLICK HERE FOR A PREVIEW OF RED CYLINDER TOOL BIT

https://codepen.io/Maximusssssu/pen/dPGyrrP?editors=1000

https://drive.google.com/file/d/1knlg1YN5MFQIG8uY8YmnXAPHmysvKQ-Y/view?usp=sharing

Dear readers, I have created an interactive webpage where users can upload an STL file and also move a red cylinder created at the origin in the 3d dimension (+X,-X ,+Y,-Y,+Z,-Z) . For simplicity, assume that the red cylinder is a mill bit or basically a circular knife that can cut through anything. When the user move the red cylinder into or on the surface of the STL solid, how do i create the visualization of cutting as seen in the picture of my expected outcome above.

I have provided all the necessary files including the STL model that can be downloded for testing.

  function createHole() {
    // TODO: Students should implement the cut creation functionality here
    // Hint: You'll need to:
    // 1. Check if clickedPoint and stlMesh exist
    // 2. Create a cylinder geometry for the cut
    // 3. Position it at the clicked point
    // 4. Use CSG operations to subtract the cylinder from the STL mesh
    // 5. Update the scene with the new mesh
    
    alert('CREATE CUT function needs to be implemented!');
  }

fetched video data using byte range http request not playing in html5 video element

I have a node server which serves byte range request from browser. The browser sends the request. I get 206 successful byte-range request status code. But the fetched segment is not playing in html5 video element. I am using firefox.

Error : No video with supported format or mime type found


async function fetchRange(url, startByte, endByte) {
    try {
         const response = await fetch(url, {
                             headers: {'Range': `bytes=${startByte}-${endByte}`}
                         });
                 
         const data = await response.blob(); 
         console.log(`Fetched ${data.size} bytes from ${startByte} to ${endByte}.`);
         return data;

    } catch (error) {
        console.error('Error fetching range:', error);
    }
}

// Example usage:
const fileUrl = 'http://localhost:8000/video'; // Replace with your file URL
const start = 0;
const end = 1023; // Requesting the first 1024 bytes (0-1023)

fetchRange(fileUrl, start, end)
.then(data => {
          if (data) {
             // Process the received data (e.g., display it, save it)
             console.log('Received data:', data);

             let f = new File([data],'haah',{ type: "video/mp4" })
             document.getElementById('vid2').src = URL.createObjectURL(f)
          }
});

html:

<video controls width="350" id="vid2" >
     <source src='' type="video/mp4" >
          Sorry, not supported by browser
     </source>
</video>

node server code :

if(req.url === '/video' && req.method === 'GET'){
        console.log('video get')
        //var filePath = 'audiofile2.flac';
        var filePath = "output_ah.mp4"
         var stat = fs.statSync(filePath);
         var total = stat.size;
         console.log(req.headers.range)
         var range = req.headers.range;
         var parts = range.replace(/bytes=/, "").split("-");
         var partialstart = parts[0];
         var partialend = parts[1];
         var start = parseInt(partialstart, 10);
         var end = partialend ? parseInt(partialend, 10) : total-1;
         //console.log(start,end)
         var chunksize = (end-start)+1;
         var file = fs.createReadStream(filePath, {start: start, end: end});
         res.writeHead(206, {
             'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
             // 'Content-Length' : total,
             'Accept-Ranges': 'bytes', 
             'Content-Length': chunksize,
             'Content-Type': 'video/mp4'
             // 'ETag' : '"'+"abcd-efgh"+'"'
         });
         file.pipe(res)
     }

I got this error in React – “Uncaught TypeError: Cannot read properties of undefined (reading ‘match’)” can someone help me please?

While creating a video game search app I ran into a problem, I’m using a separate API and when you click on a searched game card it then should take you to a new page showing games images and a brief info about the game. For some reason I get this this error “Uncaught TypeError: Cannot read properties of undefined (reading ‘match’)” for my GameDetails component (at createParagraphs (GameDetails.jsx:8:33) to be exact. It shows an error near a regex conversion where I try to convert the long text I get from API into 3 paragraph text. I think I wrote the regex correctly.

I searched the internet for answers but I didn’t get one or I just don’t understand it with different examples since I’m still a noob at coding 😀 I’ll leave the code to my GameDetails.jsx component below if you have more questions ask away, I really wanna get to the bottom of this, solving problems is like defeating a hard Souls-like boss, it’s addicting and releaving 😀

import { useEffect, useState } from "react";
import useFetch from "../hooks/useFetch";
import { fetchGameData } from "../api";
import ScreenshotCarousel from "./ScreenshotCarousel";
import Spinner from "./Spinner";

function createParagraphs(inputString) {
  const sentences = inputString.match(/[^.!?]+[.!?]+/g) || [];

  const paragraphs = [];

  for (let i = 0; i < sentences.length; i += 3) {
    const paragraph = sentences
      .slice(i, i + 3)
      .join(" ")
      .trim();
    paragraphs.push(paragraph);
  }

  return paragraphs;
}

export default function GameDetails({ currentGame, goBack }) {
  const [description, setDescription] = useState([]);

  const { data, loading, fetchData, error, reset } = useFetch(() =>
    fetchGameData({ gameSlug: currentGame.slug })
  );

  useEffect(() => {
    (async () => {
      await fetchData();
    })();
  }, []);

  useEffect(() => {
    if (data) {
      const rawDescription = data.description_raw;
      const paragraphs = createParagraphs(rawDescription);

      setDescription(paragraphs);
    }
  }, [data]);

  return (
    <section>
      <button className="main-button flex" onClick={goBack}>
        <img src="./back-arrow.svg" /> <span className="mx-2">Go Back</span>
      </button>

      {loading ? (
        <div className="flex justify-center mt-4">
          <Spinner />
        </div>
      ) : (
        <div className="mt-4">
          <div className="w-full relative">
            <div className="absolute inset-0 bg-gradient-to-b from-black via-transparent to-transparent opacity-80"></div>
            <h1 className="text-gray-200 text-2xl absolute top-5 left-5">
              {currentGame.name}
            </h1>
            <img
              className="w-full h-40 object-cover rounded-md"
              src={currentGame.background_image}
            />
          </div>
          <div className="">
            {data && (
              <div className="text-gray-300">
                {description.map((paragraph, index) => (
                  <p className="mt-2" key={index}>
                    {paragraph}
                  </p>
                ))}
              </div>
            )}

            <div className="w-full flex flex-col items-center p-4 h-96">
              {currentGame.short_screenshots.length !== 0 && (
                <ScreenshotCarousel
                  screenshots={currentGame.short_screenshots.slice(0)} 
                />
              )}
            </div>

            <div className="grid grid-cols-2 py-4">
              <div className="flex flex-col">
                <h2 className="text-gray-300 text-xl">Genres</h2>
                <ul className="flex flex-wrap gap-2 py-2">
                  {currentGame.genres.map((genre) => (
                    <li className="genre-pill" key={genre.name}>
                      {genre.name}
                    </li>
                  ))}
                </ul>
                <h2 className="text-gray-300 text-xl">Platforms</h2>
                <ul className="flex flex-wrap gap-2 py-2">
                  {currentGame.platforms.map((platform) => (
                    <li key={platform.platform.name} className="platform-pill">
                      {platform.platform.name}
                    </li>
                  ))}
                </ul>
              </div>
              <div className="flex justify-center items-center">
                <button
                  className="main-button flex items-center"
                  onClick={() =>
                    window.open(
                      `https://google.com/search?q=where+to+buy+${currentGame.name}`,
                      "_blank"
                    )
                  }
                >
                  <span className="ml-4 mr-2">Purchase</span>
                  <img src="./shopping-cart.svg" className="size-6 mr-4" />
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

I tried checking for errors in my syntax or my regex writing but I couldn’t find anything. I’ve tried googling for solutions of this problem but nothing came up that was similar to my case :/

How would someone perform filtering, paging, and other OData capabilities on in-memory data in Node.js?

I have a requirement to implement OData endpoints in Node.js. In my scenario, the underlying data will be sourced from API calls rather than a direct database connection, essentially returning large payloads of data to the function in which the OData capabilities would, unfortunately, need to operate off of in-memory data (no database pushdown, unfortunately.)

What would the code look like to accomplish something like this?

swiper.js w/ coverflow causing ‘mouse’ problems?

sceenshot

<html>
    <head>
        <style>
            .swiper-slide {
                width: 75px !important;
                cursor: no-drop;
            }
        </style>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@12/swiper-bundle.min.css" />
        <script src="https://cdn.jsdelivr.net/npm/swiper@12/swiper-bundle.min.js"></script>
    </head>

    <body>
        <div class="swiper photoContainer swiper-horizontal" style="height: 75px; width: 300px">
            <div class="swiper-wrapper">
                <div class="swiper-slide">
                    <img src="graphics/advFeature.png" />
                </div>
                <div class="swiper-slide">
                    <img src="graphics/advFeature.png" />
                </div>
                <div class="swiper-slide">
                    <img src="graphics/advFeature.png" />
                </div>
                <div class="swiper-slide">
                    <img src="graphics/advFeature.png" />
                </div>
                <div class="swiper-slide">
                    <img src="graphics/advFeature.png" />
                </div>
                <div class="swiper-slide">
                    <img src="graphics/advFeature.png" />
                </div>
            </div>
        </div>

        <script>
            photoSwiper = new Swiper(".photoContainer", {
                direction: "horizontal",
                nested: true,
                slidesPerView: "auto",
                centeredSlides: true,
                effect: "coverflow",
                coverflowEffect: {
                    rotate: 20,
                    slideShadows: true,
                    depth: 250
                    //stretch: 0,
                },
                spaceBetween: 1
            });
        </script>
    </body>
</html>

with the code above, recognition of a slide in css (or for a click event etc) is sporadic. i had working code in an older version where i could hover or click on ANY visible portion of a slide, even partly covered and far to one side, and all recognition of the correct slide worked as expected. now some (most) seem to be ignored, and which ones work change as you swipe the content. even the active slide sometimes won’t be ‘noticed’.
i have tried all kinds of suggestions, like z-indexing, on:click event in the swiper init, slidetoactive etc:false.

note that if i take out coverflow works fine immediately!

in the screenshot, only the third slide, the right half of the fifth, and the sixth one seem to be recognized; cursor changes.

it’s as if there is a disconnect between normal browser/click/touch/mouse registration and the slides now…

How do I use localStorage to save a shopping cart in JavaScript? [duplicate]

I’m building a simple shopping cart website as a beginner project, and I want to use localStorage so that the user’s cart items are not lost when the page is refreshed.

So far, I understand how to add items to the cart in JavaScript, but I don’t know how to save them in localStorage and then load them back when the page reloads.
When I refresh the page, the cart data doesn’t load back properly. It just shows as [object Object] or a string instead of the actual array of items.
I tried writing some code before, but I don’t remember exactly how I did it since it didn’t work and I almost gave up. Now I want to learn the correct way to do it.

What I’m expecting:
• Save the cart (an array of items) into localStorage.
• Retrieve the cart correctly when the page reloads.
• Keep the items in the cart persistent across page refreshes.

How can I properly implement this with JavaScript?
what I’ve tried:

localStorage.setItem('panier', JSON.stringify(table[0].innerHTML));
localStorage.setItem('cout', cout_total.toString());
// Au chargement de la page, restaurer le panier
window.addEventListener('load', () => {
    const panierSauvegarde = JSON.parse(localStorage.getItem('panier'));
    const savedTotal = localStorage.getItem('cout_total');

    
});
function mettreAJourLocalStorage() {
    const lignes = table[0].querySelectorAll('tr');
    const panier = [];

    lignes.forEach(row => {
        const nom = row.querySelector('p')?.textContent;
        const prix = row.querySelector('#prix')?.textContent?.replace(' $', '');
        const unite = row.querySelector('#unite')?.textContent?.split(' x ')[0];
        if (nom && prix && unite) {
            panier.push({
                nom,
                prix: parseInt(prix),
                quantite: parseInt(unite),
            });
        }
    });

    localStorage.setItem('panier', JSON.stringify(panier));
    localStorage.setItem('cout_total', cout_total.toString());
}

Better way to override methods on an instance of a JavaScript class

In our JavaScript web app, we use a custom-made component framework. All of our components are defined as classes using the class syntax.

We can make child classes that inherit the parents, and they can override methods that call the parent method with the super keyword.

However, we very frequently want to create individual instances of a class and override methods on that one instance, without writing up the boilerplate to make a new class that only has one instance.

Here’s an example of how we do it:

class Component {
    constructor(){ }

    myMethod() {
        // Do stuff...
    }
}

class SelectBox extends Component {
    constructor(){ super(); }

    myMethod() {
        super.myMethod();
        // Do more stuff afterwards
    }
}

// This one is normal and doesn't need overrides
let mySelectBox = new SelectBox();

// These next 2 override the same method differently
let mySelectBox1 = new SelectBox();
mySelectBox1.myMethod = function() {
    this.__proto__.myMethod.call(this);
    // Do yet more stuff on this one instance
};

let mySelectBox2 = new SelectBox();
mySelectBox2.myMethod = function() {
    this.__proto__.myMethod.call(this);
    // Do some different stuff on this other instance
};

// Defining a new class for each instance would work, but it's less concise
class MySelectBox3 extends SelectBox {
    constructor() {
        super();
    }

    myMethod() {
        super.myMethod();
        // Do yet more stuff on this one instance
    }
}
let mySelectBox3 = new MySelectBox3();

Recently, our SonarQube instance has started warning us about the __proto__ property being deprecated. I’m aware of Object.getPrototypeOf(), but that appears to do the same thing but with words.

I’ve tried using super in mySelectBox1.myMethod() but apparently that only works inside the class syntax, because I get Uncaught SyntaxError: 'super' keyword unexpected here.

Is there a cleaner way to extend a class by overriding methods on a single instance of that class, without having to rely on the deprecated __proto__ property?

Alternatively, is there a concise way to make a class that has only a single instance without filling up our codebase with a lot of boilerplate?

Is it really safe to work with arrays inside setTimeout/event handlers?

I need to access the same array from main thread and multiple setTimeout/event handlers? May array operation interrupt another array operation when it is called from, setTimeout/event handler function?

In another words, is situation like this possible:

let a = [];

Main "thread" calls: a.push(5)

While a.push(5) is not finished, setTimeout/event handler called

handler calls a.push(4), interrupting it in the middle, while a.push(5) isn't finished
*some bad things and undefined behavior happen*

If it’s unsafe, please tell me how to do it in a safe way.

Apply css just to number and symbols

Apply css just to digits
How to apply CSS only to numbers in paragraph? (without <span>)
How to apply css to only numbers in a text inside/or any <p><p> element?

When we look at the other questions above, there are only numbers and the code I got from there is below, how can I add symbols(color:blue) in addition to numbers?

$('code').html(function(i, v){
    return v.replace(/(d+)/g, '<span class="number">$1</span>');
});
.number {
    color: red;
}
<script src= "https://code.jquery.com/jquery-2.2.4.min.js"></script>

<code>z*4rc9v3@P+D)m2k5y</code>