How to Automatically Select the Highest Quality YouTube Thumbnail with ‘react-lite-youtube-embed’

I’m using the react-lite-youtube-embed library to embed YouTube videos on my site. However, I’m running into an issue with the resolution of the video thumbnails. I want to ensure that the highest quality thumbnail available is used as the poster image.

Here’s the relevant part of my code:

<LiteYouTubeEmbed
  id={videoId}
  poster={resolution}
/>

To address this, I’ve come up with the following workaround:

// CSS import
import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';

// React imports
import { useState } from "react";
import Image from "next/image";

const Video = ({ videoId }) => {
    const [resolution, setResolution] = useState("maxresdefault");

    const handleError = () => {
        // Fallback to a lower resolution thumbnail
        setResolution("hqdefault");
    };

    return (
        <div>
            <Image
                src={`https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`}
                height={0}
                width={0}
                onError={handleError}
            />
            <LiteYouTubeEmbed
                id={videoId}
                poster={resolution}
            />
        </div>
    );
};

export default Video;

This approach initially attempts to load the maxresdefault thumbnail and falls back to the hqdefault thumbnail if the higher resolution image is unavailable.

Question

Is there a more efficient or reliable way to achieve this? Ideally, I want to avoid manual fallbacks and have the component automatically select the highest quality available thumbnail (without fetching the data).

What did I try?

I tried preloading the highest resolution thumbnail (maxresdefault) using an component from next/image. If the high-resolution thumbnail fails to load, I use the onError handler to switch to a lower resolution (hqdefault).

What was I expecting?

I was hoping for a more seamless way to automatically select the highest quality available thumbnail without relying on manual fallbacks or extra components. Ideally, I want the react-lite-youtube-embed component to handle this internally (without fetching the data).

Why Does My ‘index.html’ Show a “Page Not Found” Despite Having Content in ‘main-content’ After Running JavaScript?

I’m encountering an issue where, after loading my index.html file, the page displays a “Page not found” message along with a button to return to the homepage, even though the index.html file contains valid content within the main-content section. It seems that some of the JavaScript files I’m using might be causing this problem. After certain checks, the JavaScript might be clearing the main-content and adding the “Page not found” message and return button. How can I troubleshoot this issue and ensure that the main-content is properly displayed without being overridden by the “Page not found” error?

I’ve tried several solutions, but nothing seems to work. Below is how the JavaScript files are being loaded in the index.html file:

<link rel="preload" href="/c0698a9.js" as="script">
<link rel="preload" href="/e59be96.js" as="script">
<link rel="preload" href="/8923b7f.js" as="script">
<link rel="preload" href="/e27e33b.js" as="script">
<link rel="preload" href="/33dc20f.js" as="script">
<link rel="preload" href="/8b3220f.js" as="script">
<link rel="preload" href="/5f73798.js" as="script">

And at the end of the index.html body:

<script src="/c0698a9.js" defer></script>
<script src="/33dc20f.js" defer></script>
<script src="/8b3220f.js" defer></script>
<script src="/5f73798.js" defer></script>
<script src="/e59be96.js" defer></script>
<script src="/8923b7f.js" defer></script>
<script src="/e27e33b.js" defer></script>

I’ve uploaded the JavaScript files to Google Drive, and you can access them here.

I would really appreciate any help!

Why is Auth0-angular not reading the authentication state

In angular i have in my app component a nav bar like this.

<div class="navbar">
    <button *ngIf="_auth.isAuthenticated$ | async; else outBtn" (click)="_auth.logout()">
      <i class="material-icons">logout</i>
      </button>


<ng-template #outBtn>
  <button (click)="_auth.loginWithPopup()">
    <i class="material-icons">login</i>
    </button>

</ng-template>


</div>

TS

import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { AuthService } from '@auth0/auth0-angular';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private router: Router, public _auth: AuthService) {}
}

and the app module

imports: [BrowserAnimationsModule,
    IonicModule.forRoot(),
    AuthModule.forRoot({
      domain: 'dev-zipmnrlg5gitpplk.us.auth0.com',
      clientId: '2muizfciYjTGkYfr4n1Y3JZOB7dCGljG',
      authorizationParams: {
        redirect_uri: window.location.origin
      }
    }),

  ]

I was expecting that when the user is not authenticated the login button appears and when they are the logout button appears. The app seems to not be able to read the authentication state and always says the user is not authenticated. Looking at the Auth0 dashboard i could see that the user login is a success. and it I click the login button after I logged in it quickly redirects, so i know the user is logged in.

Why is angular not reading the authentication state ?

How to manage multiple instances of the same subservice type with unique separators in a dynamic JavaScript table?

I am working on a web application where users can add multiple instances of the same subservice type to a table. Each instance should create a new separator with the subservice name in the table. The problem arises when I add the same subservice type multiple times with different names. Only the last name is displayed in the separator, and the previous instance’s line items are not shown.

I tried to generate unique IDs for each subservice instance and ensure that each separator is associated with the correct instance. I expected that each subservice instance would have its own separator and display all related line items. However, the separator only displays the last added instance’s name, and only its line items are shown in the table.

Current Code:
Here is my code for adding a new subservice and updating the separator name in the LV.

function addNewSubService(service) {
        const subserviceContainer = document.getElementById(`${service}-subservices`);
        if (!subserviceContainer) {
            console.error(`Container für ${service} nicht gefunden`);
            return;
        }

        const index = subserviceContainer.children.length;
        const subserviceInstanceId = generateSubserviceInstanceId(service, index);  // Eindeutige ID generieren
        addSubService(service, index, subserviceInstanceId);

        const nameElement = document.getElementById(`${service}-name-${index}`);
        if (nameElement) {
            nameElement.addEventListener('input', () => updateLvSeparator(service, nameElement.value));
        }

        // Füge die neue Teilleistung dem Leistungsverzeichnis hinzu
        const teilleistungId = getTeilleistungenFromOffer({ subservices: [{ type: service.replace('-', '_'), instance_id: subserviceInstanceId }] });
        loadLeistungsverzeichnis(teilleistungId, true);  // Wichtig: append = true, damit bestehende Teilleistungen nicht überschrieben werden
    }

function updateTeilleistungName(service, index, uniqueId) {
        const serviceName = document.getElementById(`${service}-name-${index}-${uniqueId}`).value;
        console.log(`Updating teilleistung name: ${serviceName} for service: ${service}, index: ${index}, uniqueId: ${uniqueId}`);

        // Finde den richtigen Separator mit der passenden uniqueId
        const separatorRow = document.querySelector(`tr.table-secondary[data-subservice-id="${uniqueId}"]`);
        if (separatorRow) {
            separatorRow.innerHTML = `<td colspan="7">Teilleistung ${serviceName}</td>`;
        }
    }

function addLvEntry(serviceType, serviceName) {
        console.log(`Adding LV entry: ${serviceType}, serviceName: ${serviceName}`);

        const lvBody = document.getElementById('lv-body');
        const tr = document.createElement('tr');
        tr.classList.add('teilleistung-entry');
        tr.dataset.serviceType = serviceType;

        tr.innerHTML = `
        <td colspan="7" class="teilleistung-header">Teilleistung ${serviceName}</td>
    `;

        lvBody.appendChild(tr);
    }

function generateSubserviceInstanceId(service, index) {
        return `${service}-${index}-${Date.now()}`;
    }

function loadLeistungsverzeichnis(teilleistungen, append = false) {
        fetch(`/api/leistungsverzeichnis?teilleistungen=${teilleistungen}`)
            .then(response => response.json())
            .then(data => {
                const lvBody = document.getElementById('lv-body');

                // Wenn nicht angehängt wird, clear das LV-Body
                if (!append) {
                    lvBody.innerHTML = '';
                }

                const existingLvIds = new Set();
                lvBody.querySelectorAll('tr').forEach(row => {
                    existingLvIds.add(row.dataset.lvId);
                });

                let currentTeilleistung = '';
                let currentTeilleistungName = '';  // To store the name of the current subservice

                data.forEach(lv => {
                    if (!existingLvIds.has(lv.id.toString())) {
                        // Add separator if the teilleistung has changed
                        if (lv.teilleistung !== currentTeilleistung || lv.teilleistung_name !== currentTeilleistungName) {
                            currentTeilleistung = lv.teilleistung;
                            currentTeilleistungName = lv.teilleistung_name;

                            const separatorRow = document.createElement('tr');
                            separatorRow.classList.add('table-secondary');
                            separatorRow.innerHTML = `<td colspan="7">Teilleistung ${currentTeilleistung} - ${currentTeilleistungName}</td>`;
                            lvBody.appendChild(separatorRow);
                        }

                        // Create and append the LV row
                        const row = createLvRow(lv, false);
                        lvBody.appendChild(row);
                    }
                });
            })
            .catch(error => {
                console.error('Fehler beim Laden des Leistungsverzeichnisses:', error);
            });
    }

function createLvRow(lv, isSaved = false) {
        const row = document.createElement('tr');
        row.dataset.lvId = lv.lv_id ? lv.lv_id : lv.id;
        row.dataset.subserviceInstanceId = lv.subservice_instance_id;

        row.innerHTML = `
            <td>${row.dataset.lvId}</td>
            <td class="text-column"><textarea class="form-control dynamic-height" ${isSaved ? 'data-saved="true"' : ''}>${lv.text}</textarea></td>
            <td class="turnus-column"></td>
            <td class="qm-column"></td>
            <td class="ae-column"></td>
            <td class="storno-column"></td>
            <td>
                ${isSaved ? `<button class="btn btn-danger" onclick="deleteLvRow('${row.dataset.lvId}', true)">Löschen</button>` : `<button class="btn btn-danger" onclick="deleteLvRow('${row.dataset.lvId}', false)">Löschen</button>`}
            </td>
        `;

        const textArea = row.querySelector('textarea');
        if (!isSaved) {
            textArea.addEventListener('input', function () {
                adjustHeight(this);
                markLvRowAsChanged(row);  // Zeile als geändert markieren
            });

            adjustHeight(textArea);
        }

        const turnusCell = row.querySelector('.turnus-column');
        if (lv.show_turnus) {
            const turnusDropdown = createTurnusDropdown(lv.turnus);
            turnusDropdown.value = lv.turnus || 'w1';
            turnusDropdown.addEventListener('change', function () {
                markLvRowAsChanged(row);  // Zeile als geändert markieren
            });
            turnusCell.appendChild(turnusDropdown);
        }

        const qmCell = row.querySelector('.qm-column');
        if (lv.show_qm) {
            const qmInput = document.createElement('input');
            qmInput.type = 'number';
            qmInput.className = 'form-control';
            qmInput.value = lv.qm || '';
            qmInput.addEventListener('change', function () {
                markLvRowAsChanged(row);  // Zeile als geändert markieren
            });
            qmCell.appendChild(qmInput);
        }

        const aeCell = row.querySelector('.ae-column');
        if (lv.show_ae) {
            const aeCheckbox = document.createElement('input');
            aeCheckbox.type = 'checkbox';
            aeCheckbox.checked = lv.ae || false;
            aeCheckbox.addEventListener('change', function () {
                markLvRowAsChanged(row);  // Zeile als geändert markieren
            });
            aeCell.appendChild(aeCheckbox);
        }

        const stornoCell = row.querySelector('.storno-column');
        if (lv.show_storno) {
            const stornoCheckbox = document.createElement('input');
            stornoCheckbox.type = 'checkbox';
            stornoCheckbox.checked = lv.storno || false;
            stornoCheckbox.addEventListener('change', function () {
                markLvRowAsChanged(row);  // Zeile als geändert markieren
            });
            stornoCell.appendChild(stornoCheckbox);
        }

        return row;
    }

How can I adjust my code to solve this problem?

Dark mode not applied on component

I am trying to use the Dropdown from NextUI and I already configured the dark mode as per the Dark mode

I use the Dropdown but it applies using the light theme, but as per the docs, the following dark box is applied:

enter image description here

So my version I try to apply dark mode:

// app/layout.tsx


export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <React.StrictMode>
      <html lang="en">
        <body className={inter.className}>
          <NextUIProvider>
            <main className="dark text-foreground bg-background min-h-screen p-4 md:p-24">
              <Header />
              {children}
              <Footer />
            </main>
          </NextUIProvider>
        </body>
      </html>
    </React.StrictMode>
  );
}

And create a dropdown:

// app/_components/nav.tsx


export default function Nav() {
  
  return (
    <Card className="mb-5 p-0">
      <CardBody className="flex flex-row py-3 px-4 w-full">
        <div className="flex flex-auto flex-row space-x-4 ">
          ... some buttons ...
        </div>
        <div className="flex flex-auto flex-row-reverse">
          <div className="flex items-center gap-4">
            <Dropdown
              backdrop="blur"
              showArrow
              radius="sm"
              classNames={{
                base: "before:bg-default-200", // change arrow background
                content: "p-0 border-small border-divider ",
              }}
            >
              <DropdownTrigger>
                <Button variant="ghost">Open Menu</Button>
              </DropdownTrigger>
              <DropdownMenu>
                <DropdownItem>View</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        </div>
      </CardBody >
    </Card >
  )
}

Result is the Dropdown is white, which I wish black…:

enter image description here

WooCommerce add to cart button hover stucks after click

i have a wordpress website with elementor and woocommerce installed. i have created a pop up with elementor when the user click add to cart button that the pop up shows up after item successfully added to the cart. the pop up show the message that item added to the cart successfully and it has a close button. in the code i use my pp up id that when user click on the add to cart button, the pop up show. and a spinner animation shows untill the item add to the cart seccessfully and after that the pop up will show. the code is worked great, but i have a problem with it. the problem is: add to cart button stays in hover after clicked and close the pop up windos. so i have to click anywhere in the page for unhover the button. how can i fix this? here are the codes i used. i put them in elementor custom codes:

<html>
<div id="page-loading">
    <div class="loading-spinner"></div>
</div>
</html>
<script>
jQuery(function($) {
    $(document).on('click', '.add_to_cart_button', function() {
        $('#page-loading').css('visibility', 'visible');
        $(document.body).on('added_to_cart', function() {
            $('#page-loading').css('visibility', 'hidden');
            if (typeof elementorProFrontend !== 'undefined' && elementorProFrontend.modules && elementorProFrontend.modules.popup) {
                elementorProFrontend.modules.popup.showPopup({ id: 11965 });
            } else {
                console.log('Elementor Popup module is not available');
            }
        });
    });
});
</script>
<style>
#page-loading {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    visibility: hidden;
}


.loading-spinner {
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-left-color: #000;
    border-radius: 50%;
    width: 50px; 
    height: 50px;
    animation: spin 1s linear infinite;
}


@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>

i have created the product page with elementor pro and the add to cart button is also created with elementor. i styled it with elementor and it has a primary color and a hover color. the button is elementor default add to cart button named “custom add to cart butoon”.

i try the code but the button hover stays stuck after close the pop up window. i want after the butoon is clicked, the hover effect disabled.

Javascript Carousel Breaking SSRS URL String

Project:
I’m working on a screen that rotates through multiple variations of an SSRS report. I’m fairly inexperienced with JavaScript so I used a code sample from W3Schools.

Issue:
I’m feeding the string to the SSRS URL that makes the report page width. The problem is, only the first URL is changing to page width. The rest are acting like they’re set to 100% when the screen changes, but the first report is still remaining as page width when it loops back around.

Body and JavaScript:

<body>

      <div class="ReportSec">
        <container class="Cover">
        <img src="Header_Logo_Source" alt="Logo">
        </container>
        <iframe class="mySlides" src="SSRS_Source&rc:Zoom=page%20width&rs:embed=true">
        </iframe>
        <iframe class="mySlides" src="SSRS_Source&rc:Zoom=page%20width&rs:embed=true">
        </iframe>
        <iframe class="mySlides" src="SSRS_Source&rc:Zoom=page%20width&rs:embed=true">
        </iframe>
        </div>

    <script>
        var myIndex = 0;
        carousel();
            
        function carousel() {
              var i;
              var x = document.getElementsByClassName("mySlides");
              for (i = 0; i < x.length; i++) {
                x[i].style.display = "none";
              }
              myIndex++;
              if (myIndex > x.length) {myIndex = 1}    
              x[myIndex-1].style.display = "block";  
            setTimeout(carousel, 10000); // Change iframe every 10 seconds
        }
    </script>    

</body>

I’ve tried changing the iframes to 3 of the same just to see if I was missing a bracket or something, but it is still failing to set to page width upon increment. I also tried adding a location.reload() to the increment, but that was just causing the page to reload indefinitely. I believe the solution is a partial reload on increment, but I haven’t worked out how to do that.

Struggling to Fully Grasp React.js Concepts—Looking for Guidance on Learning and Project Building [closed]

I’m currently learning React.js. While watching tutorials, I sometimes grasp the concepts, but other times I struggle to understand them. I usually code along with the tutorials to try and learn new concepts.

I have a basic understanding of React.js, as well as HTML5, CSS3, and JavaScript. However, I’m finding it challenging to fully understand how to implement React.js effectively in projects.

Could anyone offer advice on how to better understand React.js? Additionally, since I know the basics, how can I start building simple projects using React.js?

Any guidance or resources you could share would be greatly appreciated!

Thanks in advance!

cut subpart from html – site with javascript

for an HTML – site, say:

<body>
<div  class="current1">test1<div>test3<div class="current2">test4<div>test5</div></div></div>test2</div>
<div>test50<div>test51</div><div>test53</div></div>

</body>

I want to code a javascript (or jQuery) that returns a subpart of
the page. In the above page I want the div -tag with the class

“current2”

and all the child nodes to be shown only.

I tried something like:

var pClassList = document.getElementsByTagName("body");

for (var i = 0; i < pClassList[0].childNodes.length; i++) {  

}

but of course it does not iterate over all elements.
Does somebody has an approach ?
Any infos, hints, how tos are welcome!

Looking forward to your help!

I tried to extract the html subpart wih different javascript functions such as getElementsByTagName,childNodes but it never worked.

How to pause every ticking setTimeout and setInterval timer collectively – then unpause/resume/continue when needed

For modern web apps, simulating an app freeze/unfreeze can become necessary. One example is when you don’t want the user to miss seeing any of the dynamic content that your page/screen/website/app has to offer when he/she navigates away from the browser tab.

In such cases the desired behavior can be achieved by

  1. Pausing all CSS animations using .style.animationPlayState="paused"
  2. Pausing all video and audio using .pause()
  3. Also pausing all setTimeout and setInterval timers somehow(!)

So the question is simply HOW?


Note that a coherent answer to this particular question does not exist under any of the following related titles: 3969475 24724852 21277900 11563382 72751790 41604614

React project works in desktop but doesn’t in mobile

Sorry I’m new in React and I don’t understand why a Spotify practice project works perfectly in my pc, but not in my mobile phone. It should show the songs you search by name.

I share with you the link to the GitHub repository and the Netlify website:
Netlify
GitHub repository

If you click in “Submit” it sends a GET request to the Spotify API and shows you 10 songs.
Desktop screenshot
If I click it using the responsive mode of the developer tools, it works. But if I try it from a mobile phone or emulator it doesn’t.

Sorry I’m new and thanks for trying or helping.

The template vue-admin-template still be used now?

Today I was intended to develop a new project base on the vue-admin-template,so I downloaded the zip and then used it.Firstly I used ‘npm install’,however,it threw an error.So I used ‘cnpm install’ the second time.But when I used ‘npm run dev’,it threw an error again,which told me that there is no module ‘chokidar’.
error
I was confused that I looked up github,found that this project has been nobody to maintain for a long time.
vue-admin-template

So how could I solve this problem?Who can recommend some latest templates?

React: console.log in button click handler not showing updated state

I am building a React application where I have a button that should log the current state to the console. However, the console.log inside the button’s onClick handler always logs the initial state, not the updated one. Here’s my code:

export default function App() {
  const [users, setUsers] = React.useState([]);
  const [name, setName] = React.useState('');

  const addUser = () => {
    const obj = {
      name: 'old user name',
      updateName: (
        <button onClick={() => setName('new user name')}>update name</button>
      ),
      showName: <button onClick={() => console.log(name)}>show name</button>,
    };
    setUsers([obj, ...users]);
  };

  return (
    <div>
      <button onClick={addUser}> add user</button>
      {users &&
        users.map((user) => (
          <div>
            {user.name}
            {user.updateName}
            {user.showName}
          </div>
        ))}
    </div>
  );
}

When I click the “Update Name” button, it updates the name state to “new user name” as expected. However, when I click the “Show Name” button, it logs the initial state of name (an empty string) instead of the updated state (“new user name”).

I moved the console.log call to a separate function outside the component, but it still logs the initial state.

How can I make the console.log inside the button’s onClick handler reflect the updated state?

Any help would be appreciated!

React Quill how can i use highlight.js

i am using react quill and i want to use highlight.js for abap programming language. I tried like this but it didn’t work.

import hljs from 'highlight.js';
import "highlight.js/styles/github.css";

  const modules = useMemo(() => ({
        syntax: {
      highlight: text => hljs.highlightAuto(text).value
    },
    toolbar: {
      container: [
        [{ header: [1, 2, false] }],
        ['bold', 'italic', 'underline'],
        [{ list: 'ordered' }, { list: 'bullet' }],
        ['link', 'image', 'code-block',],
        [{ 'color': [] }, { 'background': [] }], 
      ],
      handlers: {
        image: handleImageUpload,
      },
      clipboard: {
        matchVisual: false, 
      }
    }
  }), []);

Can I execute commands using Node JS that alter environment to executing shell?

I use Node JS to wrap internal tools to make my work context faster when using these tools.
However
It has one command that I wish to execute in the shell (cmd) I am in so it ….
Sets up environment variables and changes to a specific drive and directory.

I know about spawn and fork and exec and their sync methods.
I use these to run little batch files and collect the output.

However, if I run the command, it might do the right execution but as soon as the node js script completes the environment and directory are NOT set (it was in another process)

I wish to execute the command in the shell I am in.
Can I do that?

Please no I think if you do this type replies.

If you have done what I am describing, please be clear about what steps you have to take to acquire the result I want.