Replacing div content with JavaScript – YouTube sidebar

I try to replace “opened persistent” with “persistent” on:

<div id="contentContainer" class="style-scope tp-yt-app-drawer" position="left" swipe-open style="transition-duration: 0ms;" opened persistent>

Any help much appreciated.

So far doesn’t work with the below:

document.getElementById('contentContainer').innerHTML = '';
var h1 = document.createElement('h1'); h1.innerHTML = “persistent; document.getElementById('contentContainer').appendChild(h1);

Event delegation on non nested elements

I’m using Bootstrap group radio button on which I would like to write event delegation.

<div class="btn-group" role="group" aria-label="Basic radio toggle button group">
  <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked>
  <label class="btn btn-outline-primary" for="btnradio1">Radio 1</label>

  <input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off">
  <label class="btn btn-outline-primary" for="btnradio2">Radio 2</label>

  <input type="radio" class="btn-check" name="btnradio" id="btnradio3" autocomplete="off">
  <label class="btn btn-outline-primary" for="btnradio3">Radio 3</label>
</div>

Since the labels are not nested in the button, the following is not returning the inputs.

event.target.closest('.btn-check');

Is there a proper way to write event delegation on this type of non-nested elements?

Sort numbers and NaN conditionally [duplicate]

I try to sort example array:

const array = [5, 9, NaN, 3, 15];

My expected result is:

const expected = [3, 5, 9, 15, NaN];

So the numbers are sorted ascending and the NaN values are at the end.

I tried with simple

const res = array.sort((a, b) => a - b);

or

const res = array.sort((a, b) => {
   if (a > b) return 1;
   if (b > a) return -1;
   return 0;
});

But none work. Side question – why the result is the same in both cases?

const array = [5, 9, NaN, 3, 15];

const res1 = array.sort((a, b) => a - b);
const res2 = array.sort((a, b) => b - a);

console.log(res1, res2);

How to place an image inside a SVG shape? [duplicate]

I have the following shape:

enter image description here

<svg width="64" height="64" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
<rect width="64" height="52" rx="4.66667" transform="matrix(-1 0 0 1 64 0)" fill="white"/>
<path d="M15 52H29L15 64V52Z" fill="white"/>
</svg>

I am trying to put an image inside this shape but I don’t want the image to overflow. I’d like to get something like the image below but instead of red background I’d like it to be a real image:

enter image description here

I already tried a few things:

<svg width="581" height="692" viewBox="0 0 581 692" fill="none" xmlns="http://www.w3.org/2000/svg">
  <clipPath id="cp">
    <use href="#thePath" />
  </clipPath>
  <rect width="64" height="52" rx="4.66667" transform="matrix(-1 0 0 1 64 0)" fill="white" />
  <image clip-path="url(#cp)" href={avatar} width="64" x="0" y="0" />
  <path d="M15 52H29L15 64V52Z" fill="white" />
</svg>

but that gives me this:
enter image description here

Can you please help me figure it out?

Thanks!

Issue with creating a tree with lines in HTML by modifying the Angular material Tree

I try to create a Tree with lines using the Angular material tree component.
The goal is to have a Tree with lines in order to see the sources of each Tree leaf. As you will able to see in the stackblitz i just adding some element to show the border for each node

I almost got it to work, but i have this issue as you can see here with the group lines, since the lines should appear the same as the root:

enter image description here

Should be like this:

enter image description here

Any help solving this issue will be highly appreciat.

Library or API to provide URL suggestions

I’m searching something to provide URL suggestion in my web app.
For instance, the input could be yout and it will return www.youtube.com and other possible match.

I’ve searched multiple times and I haven’t found something correct. Does anyone know something that can achieve that?

Thx

I’ve an error in my react-project(I’m doing an amazon-clone)

ERROR
undefined is not iterable (cannot read property Symbol(Symbol.iterator))
TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
at Header (http://localhost:3000/static/js/bundle.js:400:18)
at renderWithHooks (http://localhost:3000/static/js/bundle.js:35333:22)
at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:38619:17)

This is my header.js

import React from "react";
import "./Header.css";
import ShoppingBasketIcon from "@mui/icons-material/ShoppingBasket";
import StorefrontIcon from "@mui/icons-material/Storefront";
import SearchIcon from "@mui/icons-material/Search";
import { Link } from "react-router-dom";
import { useStateValue } from "./StateProvider";
function Header() {
  const [{ basket }, dispatch] = useStateValue();
  return (
    <div className="header">
      <Link to="/" style={{ textDecoration: "none" }}>
        <div className="header_logo">
          <StorefrontIcon className="header_logoImage" fontSize="large" />
          <h2 className="header_logoTitle">eShop</h2>
        </div>
      </Link>
      <div className="header_search">
        <input type="text" className="header_searchInput" />
        <SearchIcon className="header_searchIcon" />
      </div>
      <div className="header_nav">
        <div className="nav_item">
          <span className="nav_itemLineOne">Hello Guest</span>
          <span className="nav_itemLineTwo">Sign In</span>
        </div>
        <div className="nav_item">
          <span className="nav_itemLineOne">Your</span>
          <span className="nav_itemLineTwo">Shop</span>
        </div>
        <Link to="/checkout" style={{ textDecoration: "none" }}>
          <div className="nav_itemBasket">
            <ShoppingBasketIcon />
            <span className="nav_iteminTwo nav_basketCount">
              {basket.length}
            </span>
          </div>
        </Link>
      </div>
    </div>
  );
}
export default Header;

This is my project on github

I’ve tried to install the latest versions of react-dom and etc, cause I’m watchin a tutorial how to create an amazon-clone and I did the same things like in tutorial, but my code doesn’t work

Getting Internal Server Error (HTTP 500) when Trying to Query Smart Bin by binId in Node.js Application

I’m encountering an issue with my Node.js application, which serves as an API for querying smart bins. I recently updated the route to allow querying by binId instead of id, and I’m now facing an “Internal Server Error” (HTTP 500) when making GET requests.

Here’s what my route and controller look like:

Route (Express.js):

router.get('/:binId', smartBinController.getSmartBinByBinId);

Controller (Node.js):

const getSmartBinByBinId = async (req, res) => {
  try {
    const { binId } = req.params;
    const { binLevel, binOrientation, binLocation, binName } = req.query;

    const smartBin = await SmartBin.getSmartBinByBinId(binId);

    if (!smartBin) {
      return res.status(404).json({ error: 'Smart bin not found' });
    }

    if (binLevel) {
      smartBin.binLevel = binLevel;
    }
    if (binOrientation) {
      smartBin.binOrientation = binOrientation;
    }
    if (binLocation) {
      smartBin.binLocation = binLocation;
    }
    if (binName) {
      smartBin.binName = binName;
    }

    await smartBin.save();

    res.status(200).json({ message: 'Smart bin updated successfully', smartBin });
  } catch (error) {
    console.error('Error updating smart bin:', error);
    res.status(500).json({ error: 'Failed to update smart bin' });
  }
};

Model:

const smartBinSchema = new mongoose.Schema({
  binId: {
    type: String,
    required: true,
    unique: true,
  },
  binLevel: {
    type: Number,
    required: true,
  },
  binOrientation: {
    type: String,
    required: true,
  },
  binLocation: {
    type: String,
    required: true,
  },
  binName: {
    type: String,
    required: true,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  updatedAt: {
    type: Date,
    default: Date.now,
  },
});


const getSmartBinByBinId = async (binId) => {
  try {
    const smartBin = await SmartBin.findOne({ binId });
    return smartBin;
  } catch (error) {
    throw error;
  }
};

module.exports = {
  getSmartBinByBinId,
};

It’s works well with querying by id:
https://iot-smart-bin.onrender.com/api/smartbin/64a9a7d7fbde3940ba8f132f?binId=bin001&binLevel=90&binOrientation=Upright&binLocation=Kuje%prison&binName=Kuje%Prison.

Querying by binId that’s not working: https://iot-smart-bin.onrender.com/api/smartbin/bin001?binLevel=80&binOrientation=Upright&binLocation=Kuje%prison&binName=Kuje%Prison

Github Link: https://github.com/blcdevs/smart-iot-bin

I’ve checked my server logs, but the error message is not very descriptive. I suspect there might be an issue in my route, controller, or possibly with my MongoDB database. Can anyone help me diagnose and resolve this “Internal Server Error” issue?

Any insights, suggestions, or debugging tips would be greatly appreciated!

How can I use Markdown in JSON on a Quarto website?

I implemented a simple flashcard app for my Quarto website, following a nice YouTube tutorial. The app works, but I want to use Markdown for the flashcard contents (to format LaTeX equations, links etc.).

My current implementation: I store the data for my flashcards in JSON format in the file flashcards.js and naively use Markdown here, but this is not interpreted when I render my Quarto website:

var flashcards = [
  {
    "Q":"**front1** $a^2$ [link](destination.qmd)",
    "A":"back1"
  },
  {
    "Q":"front2",
    "A":"back2"
  },
  {
    "Q":"front3",
    "A":"back3"
  },
]

My .qmd is

---
format: 
  html:
    include-after-body: 
      - text: |
          <script src = "flashcards.js"></script>
          <script src = "reveal.js"></script>
---

<body onload = "getRandomCard()">
<div class = "question"></div>
<div class = "flashcard-button">
<button class = "check">Show solution</button>
<button class = "next">Next Card</button>
</div>
<div class = "answer"></div>
</body>

and the JavaScript to show a new flashcard and reveal the back is inside reveal.js:

const question = document.querySelector('.question');
const answer = document.querySelector('.answer');
const check = document.querySelector('.check');
const next = document.querySelector('.next');
let card = -1;
let solution = false;

function getRandomCard() {
  let random;
  do {
    random = Math.floor(Math.random() * flashcards.length);
  }
  while (card == random);
  card = random;
  question.innerHTML = `${flashcards[card].Q}`
  answer.innerHTML = `${flashcards[card].A}`
}

check.addEventListener('click', function() {
  if (solution) {
    answer.style.display = 'none';
    solution = false;
  } else {
    answer.style.display = 'block';
    solution = true;
  }
});

next.addEventListener('click', function() {
  answer.style.display = 'none';
  solution = false;
  getRandomCard();
});

So my question is: Is it possible (and if yes, how) to use Markdown (for math equations, links) in my file flashcards.js? I feel like I am missing something simple here and hope that someone can point me in the right direction.

Generic typing of callback functions in classes

This is a follow up from my last post Generic types in classes which has been perfectly answered by @jcalz. Since playing around with this solution, I highly doubt my understanding of Typescript in general. I simply can’t get my head around of what is going on and why certain things “are not working”.

However, I recently wanted to know how I could achieve a typed mapping of taskIds to their callback back functions and get a typed result. See here. I have now extended the code to

type Values<T extends string> = {[K in T]: any}
type Results<T extends string, R> = {[K in T]: R}
type Callback<T extends string> = (prev?: any, values?: Values<T>) => any


type Task<
  K extends string,
  V extends Callback<K>
> = {
  taskId: K;
  callback: V;
};


class Taskmanager<
  S extends string,
  const T extends Task<
    S,
    Callback<S>
  >
> {

  private prevTaskId?: T["taskId"];
  private values!: Values<T["taskId"]>;
  private tasks = new Map<T["taskId"], T>


  public constructor(tasks: readonly T[]) {
    tasks.forEach((task) => {
      this.tasks.set(task.taskId, task);
      this.values = {...this.values, [task.taskId]: undefined};
    });
  }


  public run<K extends T["taskId"]>(): {[ID in K]: ReturnType<Extract<T, { taskId: ID }>["callback"]>} {
    let result = {}

    this.tasks.forEach(task => {
      const prev = this.prevTaskId ? this.values[this.prevTaskId] : undefined;
      const res = task.callback(prev, this.values);
      this.values[task.taskId] = res;
      this.prevTaskId = task.taskId;
      result = {...result, [task.taskId]: res};
    })

    // Is there a better way than casting the return type?
    return result as {[ID in K]: ReturnType<Extract<T, { taskId: ID }>["callback"]>};
  }
}

// ---------------
//  TEST
// ---------------
const tm = new Taskmanager([
  {
    taskId: "defineValue",
    callback: (prev, values) => {
      return 1;
    },
  },
  {
    taskId: "usePrev",
    callback: (prev) => {
      return "hello " + prev;
    },
  },
  {
    taskId: "useValue",
    callback: (prev, values) => {
      // How could I achieve type hints for `values`? Currently values: { [x: string]: any }
      // eg. values?.defineValue or values?.useValue
      // Since I have return types from the callback functions, could I also infer those? E.g. typeof values?.useValue === 'object' --> true
      return {
        prev: prev,
        usePrevVal: values?.usePrev
      }
    },
  }
]);

const results = tm.run();
// results → { defineValue: number, usePrev: string, useValue: { prev: any, useDefineVal: any } } --> this is perfect!

console.log("Results", results)
// LOG → "Results", { "defineValue": 1, "usePrev": "hello 1",  useValue: { "prev": "hello 1", "useDefineVal": 1 }} --> works as intended

Here’s a link to TS Playground

How could I get type hints for the callback values parameter? Preferably including the return type of the associated callback but having the taskIds as keys would already be good enough.

Thanks!

Swiper Coverflow Alignment Issues in React

I am implementing a coverflow effect in my carousel using swiper library. But its not working the way i need.

Here’s what i get:
enter image description here

but I need like this
enter image description here

Code I tried:

import React, { useRef } from "react";
import { EffectCoverflow } from "swiper/modules";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";

export default function App() {
  const swiperRef = useRef(null);

  const goNext = () => {
    if (swiperRef.current && swiperRef.current.swiper) {
      swiperRef.current.swiper.slideNext();
    }
  };

  const goPrev = () => {
    if (swiperRef.current && swiperRef.current.swiper) {
      swiperRef.current.swiper.slidePrev();
    }
  };

  const Box = ({ item }) => {
    return (
      <div style={{ width: "150px", height: "200px", background: "red" }}>
        Slide {item}
      </div>
    );
  };

  return (
    <div>
      <Swiper
        ref={swiperRef}
        modules={[EffectCoverflow]}
        spaceBetween={50}
        slidesPerView={5}
        centeredSlides={true}
        effect={"coverflow"}
        grabCursor={true}
        EffectCoverflow={{
          rotate: 50,
          stretch: 0,
          depth: 100,
          modifier: 1,
          slideShadows: true
        }}
      >
        {[1, 2, 3, 4, 5, 6, 7, 8].map((item, index) => (
          <SwiperSlide>
            <Box item={item} />
          </SwiperSlide>
        ))}
      </Swiper>
      <button onClick={goPrev}>Previous</button>
      <button onClick={goNext}>Next</button>
    </div>
  );
}

i can change slidesPerView={5}. It comes like this
enter image description here

I made auto to adapt to screen sizes

File System API – Adding text instead of replacing

Say I have a text file with the following content:

AAA
BBB
CCC

And I want to use the File System API to insert a new row in this file, in order to get the following:

AAA
XXX
BBB
CCC

For that I have the following code:

const [fileHandle] = await window.showOpenFilePicker()

const writable = await fileHandle.createWritable({ keepExistingData: true })
await writable.write({
  type: "write",
  position: 4,
  data: "XXX",
})
await writable.close()

However the result is the following:

AAA
XXX
CCC

Is there a way to achieve this without loading the whole content of the file in memory and then overwriting?

Facing problems in aligning horizontal scrolling website

I have build a horizontal scrolling website. live link.

NOTE: “THE WEBSITE ISN’T RESPONSIVE YET”

how to replicate the issue:
(you might be able to see a thin white line at the bottom of the home screen as well)

  1. open dev tools, there will be a white space on the top part of the website.
  2. also by resizing width in dev tools, you can see the website behaves very strangely

basic idea of How i got till here:

  1. rotated the outer wrapper div by 90deg anti-clockwise.
  2. rotated to inner-wrapper div by 90deg clockwise.

here is the code of this part of the website which contains all of the horizontal scroll logic. But if you need the complete website code i can add that as well. website is only using react no other library or framework


import React from "react";
import "./App.css"
import Intro from "./pages/Intro";
import LandingPage from "./pages/LandingPage";
import Skills from "./pages/Skills";

function App() {
  return (
    <div className="outer-wrapper">
      <div className="wrapper">

      <section className="first">
        <LandingPage />
      </section>
      <section className="second">
        <Skills />
      </section>
      <section className="third">
        <Intro />
      </section>
      <section className="fourth">
        <Intro />
      </section>
      </div>
    </div>
  );
}

export default App;

*{
  margin: 0;
  padding: 0;
  overflow-y: hidden;
}
::-webkit-scrollbar{
  display: none;
/* overflow:-moz-hidden-unscrollable */
}
.outer-wrapper{
  /* padding: 10%; */
  height: 100vw;
  background-color: black;
  transform: rotate(-90deg) translateX(-59rem);
  transform-origin: top left;
  width: 100vh;

  overflow-y: scroll;
  overflow-x: hidden;
  
}
.outer-wrapper::-webkit-scrollbar{
  /* display: none; */
  overflow: hidden;
}
.wrapper{
  height: 100vh;
  width: 400vw;
  display: flex;
  transform: rotate(90deg) translateY(-59rem);
  transform-origin: top left;
}


section{
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.first{
  background-color: #ebe8e0 ;
}
.second{
  background-color: #ebe8e0;
}
.third{
  background-color: silver;
  /* transform: rotate(-90deg); */
  /* transform-origin: top left; */
}
.fourth{
  background-color: mediumaquamarine;
}

I was trying to build a horizontal scrolling portfolio to get my first job. I tried increasing/decreasing the translate values but the alignment is still not matching properly.

how to add vlc media player into your html website

I’m facing an issue where I’d like to integrate VLC media player into my website due to its numerous features that surpass other players. However, I’m unsure about the process of adding it. I would greatly appreciate your assistance in guiding me through the step-by-step procedure. Thank you for your help.”

“I attempted to add it in a certain manner, but I encountered difficulties because I’ve never encountered the challenge of integrating VLC media player into my website before.”