How to achieve at least one property required in object recursively for nested objects in typescript

For a project I’m working on, I required my objects to be defined with at leat one of the property from the object
for example

type DraggableOptions = {
  identifier?: {
    id?: string;
    type?: string[];
  };
  modifiers?: {
    highlight?: {
      on: "dragmove" | "dragover";
      class: string;
    };
  };
}

As all the properties are optional(because I also have default options) user can just pass a empty object {} when passing the DraggableOptions which I want to restrict to define at least one property from the object.

I also found a solution for this in the following stack overflow question but it does not work for nested objects which is my requirement. So based on the solution I have found I tried to write a recursive one also but could not get it right.

I found these two particular solution to be working in my case.

type AtLeastOne<T> = {
  [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>;
}[keyof T];
type AtLeastOne<T, U = { [K in keyof Required<T>]: Pick<Required<T>, K> }> = Partial<T> &
  U[keyof U];

And I tried the following solution for recursive but they are not working

type RecursiveAtLeastOne<T> = {
  [K in keyof T]: T[K] extends object ? AtLeastOne<T[K]> : T[K];
};

and

type RecursiveAtLeastOne<T> = {
  [K in keyof T]: T[K] extends Record<string, any> ? AtLeastOne<T[K]> : T[K];
};

Can any please guide me what I’m doing wrong and what would be the right solution for this problem? Thank you so much in advance.

Btw as I am not able to write the recursive version correctly I’m using the following approach to make nested objects at least on required

export type DraggableOptions = AtLeastOne<{
  identifier?: AtLeastOne<{
    id?: string;
    type?: string;
  }>;
  modifiers?: AtLeastOne<{
    dropEffect?: "copy" | "move";
  }>;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  data?: any;
}>;

How can I create child elements radially around parent?

I have a center point that I want to add child elements to dynamically when a button is pressed. I need to create them at random degrees and ranges from the parent element (center). I am running into a few issues here:

  1. I can’t seem to append more than one element to the parent. When I view the DOM I see only one div appended.

  2. When I change the rotation of the parent element it changes the position of all child elements. Is there a better way to position these children radially from the parent?

  3. When I change the translation of the child element it affects all children. I have tried creating a new class .newDust for initial positioning with the intent on changing the class to .dust for the following logic and to disconnect it from the parent. Before I go through with this maybe a better answer to issue #2 will solve this problem.

Here is the HTML for my problem. I have a test “dust” element in place to see what happens when I create new elements and modify the center.

<body>
    <div id="playArea">
        <div id="center">
            <div class="dust">

            </div>
        </div>
    </div>
    <div>
        <button id="createDust" type="button">CREATE DUST</button>
    </div>

    <script src="main.js"></script>
</body>

CSS here:

body {
    height: 100vh;
    background-color: #3c3c3b;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    font-family: Arial;
}

#center {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #62bbc1;
    position: fixed;
    transform: rotate(45deg);
}

.dust {
    width: 10px;
    height: 10px;
    border-radius: 5px;
    background-color: #735cdd;
    position: absolute;
    transform: translate(200px);
}

.newDust {
    width: 10px;
    height: 10px;
    border-radius: 5px;
    background-color: #735cdd;
    position: relative;
    transform: translate(200px);
}

Javascript here:

// Setup variables

const createDust = document.getElementById("createDust");
const center = document.getElementById("center");
let newDust = document.createElement("div");
    newDust.className = "newDust";
let dust = document.createElement("div");
    dust.className = "dust";



let randomDegree;
let randomRange;

// Random degree generator

function randomizeDegree() {
    return Math.floor(Math.random() * 360);
}

// Random range generator


// Event listeners

createDust.addEventListener("click", () => {
    randomDegree = randomizeDegree();
    center.style.transform = `rotate(${randomDegree}deg)`;
    center.appendChild(newDust);
    newDust.style.position = 'absolute';


});

DropDownlist pai e Dropdownlist Filha no JavaScript [closed]

Como vai? Estou trabalhando na interação de um site já criado em JavaSript onde possui 2 dropwnList sendo que que o dropDownList pai é de Estados e o DropDownlist filho é de Cidades. Estou trabalhando com c# e Selenium. Criei um metodo em JavaScript que popula com sucesso o DropDownPai, mas ao inserir Estado, deveria automaticamente carregar a lista da DropDown de Cidades e isso não acontece. No modo manual funciona perfeitamente mas na interação a dropdown de cidades nao carrega. Não sei mais o que fazer para que a dropdownlist de cidades seja carregada após o selecionamento de um estado. Quero fazer um metodo em javascript com Selenium e c# ou jquery. Este só chama o estado mas deceria disparar o evento para carregar a dropdownlist de Cidades.

    string script = @"
            var dropdown = document.getElementById('select-8f54f92c-4026-42c5-7654-9d3b14a1b961');
            var estadoSelecionado = 'valorMaiusculo';
            for (var i = 0; i < dropdown.options.length; i++) {
                if (dropdown.options[i].value === estadoSelecionado) {
                    dropdown.selectedIndex = i;
                    dropdown.dispatchEvent(new Event('change'));
                    break;
                }
            }
        "
            ;

            IJavaScriptExecutor js = (IJavaScriptExecutor)browser;
            js.ExecuteScript(script);

            // Simular um clique em algum elemento após selecionar o estado "PE"
            var element = browser.FindElement(By.Id("select-8f54f92c-4026-42c5-7654-9d3b14a1b961"));
            element.Click();

Sending text+binary data in nodejs websocket

I want to send some text and binary data from nodejs to a C server over websocket. Here is the minimal code as below.

const W3WebSocket = require('websocket').w3cwebsocket;

var wsConn = null;

async function lm_send_controller_templates(dir) {
  //Create websocket client, reference https://stackoverflow.com/questions/61755518/is-it-possible-to-have-a-node-js-websocket-client
  var wsConn = new W3WebSocket('wss://192.168.1.5:4445/', '');
  
  wsConn.onerror = function(e) {
    console.log('Connection Error');
    console.log(e);
  };

  let file1 = 'datfiles.zip';
  wsConn.onopen = function(event) {

    let msg = 'commandn' + 'upload' + 'n' + 'datfiles.zip' + 'n' + 'datfiles.zip';
    wsConn.send(msg);
    
    fs.readFile(`${dir}${file1}`, '', (err, data) => {
      if (err) {
        console.error(err);
        return;
      }
    
    console.log(`read ${data.length} bytes`);
    wsConn.send('datan' + data);
      
    msg = 'commandnover';
    wsConn.send(msg);
      
    });
    
  };

  wsConn.onmessage = function(e) {
    console.log(`Rcvd data ${e.data}`);
  };
}

On C server side I am getting bigger chunk of data than expected. I suspect I am doing something wrong while sending data.

I doubt the way I send binary data. Can somebody please suggest correct way of sending binary data over websocket.

Firebase chat rerender automatically

I am making chatApp using reactjs and firebase.
Let there is user A which is I am and two user in my chat userC userB if I open user B chat and then userC chat and then if userB send me message my screen show we userB chat even I already open userC chat

My app link given below so you can understand problem properly

https://chat-app-five-pink-36.vercel.app/

Here is image below
Here is fetchChat function



const fetchChat = async () => {

        try {

            const friendChat = collection(firebaseFirestore, `chat/${currentUser.uid}/friends/${userSelected.uid}/chats`);

            const orderedChatList = query(friendChat, orderBy("timeStamp"));

            const unsubscribe = onSnapshot(orderedChatList, (snapshot) => {

                const allChat = snapshot.docs.map(doc => doc.data());

                setCurrentChat(allChat);

            });

            return () => unsubscribe();

        } catch (error) {

            console.log(error);

        }

    };

I didn’t used useEffect to render chat on change I think it’s happing becoz of onSnapshot

Inserting an array into a table – Javascript

I want to enter the data that has been provided in an array. and will connect some data. but I’m confused about how to insert it into the table.

var name_id = [1000,1001,1002];
var total = [3000,3100,3200];
var name_data = 
    {
    "1": {
        "1000": {
        "nama": "John Doe",
        "gender": "Male",
     },
    },
    "2": {
        "1001": {
        "nama": "Allen",
        "gender": "Male",
     },
    },
    "3": {
        "1002": {
        "nama": "Karin",
        "gender": "Female",
     },
    },
   }

var id_name = ""
name_id.map((c, i) => {
    id_name += `<tr>
    <td>${c}</td></tr>
`});

var total_vote=""
total.map((c, i) => {
    total_vote += `<tr>
    <td>${c}</td></tr>
`});

var valuex = (Object.values(name_data));
var name_ = Object.keys(name_data).length;
for (var x; x<valuex.length; x++) {
    console.log(valuex[x])
}
//console.log('a',name_)
//var newName = {'1000': 'John',}
//for (var x=0; x<name)




$('#table').append(`
    <tbody>
    ${id_name}
    ${total_vote}
  </tbody>
`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

here is the link for the complete code https://jsfiddle.net/dedi_wibisono17/n2ho6v3L/32/

Any idea? Thank you

How can I fetch additional data after the page is already rendered with remix?

I’m using a loader to fetch the ids of several resources and the user can select the ids of the ones they would like to load.

I haven’t found a way to pass new arguments to the loader to GET new data after the page is loaded.

Created a Stack Overflow account specifically because of this. Would super appreciate any help!!

I’ve found that remix loaders can only accept request, params, and context.

One possible solution may be passing params through the URL but I’m hoping to find a different solution because I need to be able to pass an array of ids. I also haven’t gotten this solution to work.

Another solution I explored is appending the ids with formState but that wouldn’t reload the page (so the loader wouldn’t make another request with the new params).

Export Excel Angular

I have a problem when exporting excel, the file can be downloaded but when opened it is empty. this is the code on the Frontend side:

onExportToExcelClicked() {
    const payload = {
        SNoba: this.noBa,
    };    this.http.post(`${environment.inventarisasiUrl}/api/inv/t/invent/detailsexcel`, payload, {
        responseType: 'blob' // Set response type to blob
    }).subscribe(
        (blob: Blob) => {
            const url = window.URL.createObjectURL(blob);

            const a = document.createElement('a');
            //a.style.display = 'none';
            a.href = url;
            a.download = `${this.noBa}.xlsx`;

            document.body.appendChild(a);
            a.click();

            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }

Data appears when downloading excel

How do I save info using local storage? Im building a todo list and I cant figure it out. it’s not saving the data

Hello im trying to save the data I have left comments to try to show you what ive done but I still cant figure it out. I have tried YouTube and chatgbt but it cant figure it out either. If anyone has any recommendations id really appreciate it. I have added my css, html and javascript. I tried making function to collect the data its at the bottom of the JavaScript.

//variables

const addForm = document.getElementById('add-form');
const itemList = document.querySelector('.list');
const filter = document.getElementById('filter');

addForm.addEventListener('submit', (e) => {
    e.preventDefault();
    console.log(`type ${e.type}`);

    //get input value
    const newItem = document.getElementById('input-box').value;

    //create new li method
    const li = document.createElement('li');
    li.className = 'list-item';
    //add text node with input value
    li.appendChild(document.createTextNode(newItem));
    
    //create delete button
    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'btn';
    //append text to list
    deleteBtn.appendChild(document.createTextNode('X'))
    li.appendChild(deleteBtn);

    //append li to list 
    itemList.appendChild(li);
    
    saveData();
});

// delete button 
itemList.addEventListener('click', (e) => {
        if (e.target.classList.contains('btn')) {
            if (confirm('are you sure')) {
                //parent grabs li
                const li = e.target.parentElement;
                itemList.removeChild(li);
                saveData();
            }
        }
});

//search
filter.addEventListener('keyup', (e) => {
    //convert text to lower case
    const text = e.target.value.toLowerCase();
    const items = itemList.getElementsByTagName('li');

    Array.from(items).forEach(function(item) {
        const itemName = item.firstChild.textContent;

        if(itemName.toLowerCase().indexOf(text) != -1) {
            item.style.display = 'flex';
        } else {
            item.style.display = 'none';
        }
    });
    console.log(text);
});

//save data. for local storage I cant figure out. 
// Function to save data to local storage
function saveData() {
    const items = [];
    document.querySelectorAll('.list-item').forEach(item => {
        items.push(item.firstChild.textContent); // Assuming first child is the text node
    });
}

// Function to load data from local storage
function loadData() {
    const items = localStorage.getItem('itemList');
    if (items) {
        items.forEach(item => {
            addItemToList(item);
        });
    }
}

// Call loadData on page load to initialize the list with saved items
document.addEventListener('DOMContentLoaded', loadData);
 :root {
            --container-padding: 5vw;
            --section-padding: 2vw;
            --border-radius: 0.2rem;
        }

        body,
        html {
            padding: 0;
            margin: 0
        }

        body {
            font-family: sans-serif;
            font-weight: 400;
            font-size: 16px;
            line-height: 1.1;
            color: black;
        }

        ul,
        li {
            padding: 0;
            margin: 0;
            list-style: none;
        }

        h1,
        h2,
        h3,
        h4,
        h5,
        p,
        span {
            padding: 0;
            margin: 0;
            line-height: 1.1;
        }

        h1 {
            font-family: sans-serif;
            font-weight: 400;
            font-size: clamp(1.5rem, 4vw, 2rem);
            color: white;
            line-height: 1.1;
        }

        h2 {
            font-family: sans-serif;
            font-weight: 350;
            font-size: clamp(1.2rem, 4vw, 1.8rem);
        }

        .section {
            padding-top: var(--section-padding);
            padding-bottom: var(--section-padding);
            position: relative;
            display: block;
        }

        .container {
            padding-right: var(--container-padding);
            padding-left: var(--container-padding);
            max-width: 100%;
            max-width: 100em;
            margin: 0 auto;
        }

        .row {
            display: flex;
            flex-wrap: wrap;
            position: relative;
        }

        .flex-col {
            display: block;
            width: 100%;
            order: 2;
            position: relative;
        }

        /*------------ header ----------------*/
        .header {
            width: 100%;
            background-color: green;
        }

        .header .flex-col {
            padding: 3vw 0vw 3vw 0vw;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header .search {
            border-radius: var(--border-radius);
            border: 0;
            padding: 0.5rem 5.8rem 0.4rem 0.5rem;
            font-size: 0.8rem;

        }

        .header .search::placeholder {
            color: gray;
        }

        /*------------ items ----------------*/

        .items .flex-col {
            display: flex;
            flex-direction: column;
            border: 0.5px solid grey;
            padding: 1.5rem 1rem 1.5rem 1rem;
            border-radius: var(--border-radius);
            gap: 1.5rem;
        }

        .items .flex-col .top {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .items .flex-col .top .btn-row {
            display: flex;
            gap: 0.5rem;
        }

        .items .flex-col .top .btn-row #input-box {
            border: 0.5px solid grey;
            padding: 0.4rem 1.5rem 0.4rem 0.5rem;
            border-radius: var(--border-radius);
        }

        .items .flex-col .btn {
            border: 1px solid black;
            background-color: black;
            color: white;
            border-radius: var(--border-radius);
            padding: 0.3rem 0.6rem 0.3rem 0.6rem;
            font-size: 0.8rem;
            font-weight: 300;
            pointer-events: all;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.7, 0, 0.3, 1);
        }

        .items .flex-col .btn:hover {
            background-color: rgb(93, 93, 93);
        }

        .items .flex-col .bottom {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .items .flex-col .bottom .list {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .items .flex-col .bottom .list .list-item {
            border: 0.5px solid grey;
            border-radius: var(--border-radius);
            padding: 0.8rem;
            font-size: 1rem;
            font-weight: 250;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .list .list-item .btn {
            height: 1.8rem;
            width: 1.5rem;
            background-color: red;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s cubic-bezier(0.7, 0, 0.3, 1);
        }

        .list .list-item .btn:hover {
            background-color: rgb(255, 94, 94);
        }
    <header class="header">
        <div class="container">
            <div class="row">
                <div class="flex-col">
                    <h1 class="header-title">Item Lister</h1>
                    <form id="filter" action="">
                        <input type="text" class="search" placeholder="Search Items....">
                    </form>
                </div>
            </div>
        </div>
    </header>

    <section class="section items">
        <div class="container">
            <div class="row">
                <div class="flex-col forum">
                    <form name="form" id="add-form" class="top">
                        <h2 class="title">Add Items</h2>
                        <div class="btn-row">
                            <input id="input-box" type="text">
                            <button type="submit" class="btn">Submit</button>
                        </div>
                    </form>
                    <div class="bottom">
                        <h2 class="title">Items</h2>
                        <ul class="list">
                            <li class="list-item">Item 1 <button class="btn">X</button></li>
                            <li class="list-item">Item 2 <button class="btn">X</button></li>
                            <li class="list-item">Item 3 <button class="btn">X</button></li>
                            <li class="list-item">Item 4 <button class="btn">X</button></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </section>

How to simulate typing in my textarea with Chat GPT’s API in JavaScript using real-time server-sent events

I have this code. It works perfectly in my local environment, but on live server, the whole text is shown all at once, it does not simulate typing.

Create a new EventSource object for real-time server-sent events (SSE)

    // Create a new EventSource object for real-time server-sent events (SSE)
    const source = new EventSource(url);

    // Initialize the response content and current index for displaying typed characters
    let responseContent = '';
    const streamingTextElement = document.getElementById('generated_text');
    let currentIndex = 0;

A function that types out received chunks character by character

    function typeCharacter() {
        if (currentIndex < responseContent.length - 9) {
            streamingTextElement.value += responseContent.charAt(currentIndex);
            currentIndex++;
            setTimeout(typeCharacter, 100); // Adjust the typing speed by changing the delay (in milliseconds)
        }
    }

Process the received SSE events

    // Process the received SSE events
    source.onmessage = function (event) {
        if (event.data == '[DONE]') {
            // All data received, logging it and closing the connection
            const submitButton = document.querySelector('.fmai-submit-btn');
            submitButton.disabled = false;
            document.querySelector('.loading-tea').style.display = 'none';
            
            console.log('All data received:', responseContent);
            source.close(); // Close the connection

            return;
        }

        const data = JSON.parse(event.data);

        if (data.id) {
            // Process the data message chunk
            const choices = data.choices;

            if (choices && choices.length > 0) {
                const content = choices[0].delta.content;

                responseContent += content;
                typeCharacter();

                // Auto-scroll to the bottom as new content is added
                streamingTextElement.scrollTop = streamingTextElement.scrollHeight;
            }
        } 
    };

Handling errors in receiving SSE events

    // Handling errors in receiving SSE events
    source.onerror = function (error) {
        const submitButton = document.querySelector('.fmai-submit-btn');
        submitButton.disabled = false;
        document.querySelector('.loading-tea').style.display = 'none';
        
        fmaiNotification.style.display = 'block';
        fmaiNotificationMsg.innerHTML = `We couldn't connect, try again.`;

        setTimeout(() => {
            fmaiNotification.style.display = 'none';
            fmaiNotificationMsg.innerHTML = '';
        }, 1500);

    
        // console.error('Error:', error);
        source.close(); // Close the connection
    };

How Verify Public Key With Web Crypto API

I can perform verification in Node Crypto without problem and it outputs true, but when i tried with Web Crypto it outputs false without any errors but both using same variables. I can’t use Node Crypto because code will run in CF Worker Runtime and it doesn’t supports related Node Crypto functions. Why it’s happening like this and how can i fix.

This code is using Node Crypto and outputs true.

import crypto from "crypto";

const publicKeyPEM = `-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEXjyD37iJ6K7dVWCANfrTEJkDFKZt
dlaCMOGuTE3qsy4PF3FqUnDi0EZxty8n6Mb3W3Ahj0ASkF+GwNW8C/ztdQ==
-----END PUBLIC KEY-----`;
const messageToVerify = "hello world";
const signature =
    "MEUCIENzPHGDk+t1inhAvnqPX1OYLfSltYVIv1cipjW2F3CxAiEAzTVrj5CCHChsyeAif0qM6UvX3h0U7BDHhb+XmsXwO/c=";

(() => {
    const verify = crypto.createVerify("SHA256");
    verify.update(messageToVerify);
    const verified = verify.verify(
        publicKeyPEM,
        Buffer.from(signature, "base64")
    );
    console.log(verified);
})();

This code is using Web Crypto API and outputs false.

function str2ab(str) {
    const buf = new ArrayBuffer(str.length);
    const bufView = new Uint8Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}

async function importEcdsaKey(pem) {
    const pemHeader = "-----BEGIN PUBLIC KEY-----";
    const pemFooter = "-----END PUBLIC KEY-----";
    const pemContents = pem.substring(
        pemHeader.length,
        pem.length - pemFooter.length - 1
    );

    const binaryDerString = atob(pemContents);
    const binaryDer = str2ab(binaryDerString);

    return await crypto.subtle.importKey(
        "spki",
        binaryDer,
        {
            name: "ECDSA",
            namedCurve: "P-256",
        },
        true,
        ["verify"]
    );
}

function base64ToArrayBuffer(base64String) {
    const binaryString = atob(base64String);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}

const publicKeyPEM = `-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEXjyD37iJ6K7dVWCANfrTEJkDFKZt
dlaCMOGuTE3qsy4PF3FqUnDi0EZxty8n6Mb3W3Ahj0ASkF+GwNW8C/ztdQ==
-----END PUBLIC KEY-----`;
const messageToVerify = "hello world";
const signature =
    "MEUCIENzPHGDk+t1inhAvnqPX1OYLfSltYVIv1cipjW2F3CxAiEAzTVrj5CCHChsyeAif0qM6UvX3h0U7BDHhb+XmsXwO/c=";

(async () => {
    const publicKey = await importEcdsaKey(publicKeyPEM);
    const signatureArrayBuffer = base64ToArrayBuffer(signature);
    const data = new TextEncoder().encode(messageToVerify);

    const result = await crypto.subtle.verify(
        {
            name: "ECDSA",
            hash: { name: "SHA-256" },
        },
        publicKey,
        signatureArrayBuffer,
        data
    );

    console.log(result);
})();

Vimeo player not working with WordPress DIVI Theme

I am having some trouble integrating this JSfiddle into my website

JSFiddle : https://jsfiddle.net/0dtfpamx/4/

Code :

<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/froogaloop.js"></script>
<iframe id="player1" src="https://player.vimeo.com/video/80312270?api=1&player_id=player1" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen id="video"></iframe>
<div class="show--div-20sec">
  Show me after 20 second of video play
</div>
<div class="buttons">


  <button id="play-button">Play</button>
  <button id="pause-button">Pause</button>

</div>

JQuery

$(function() {
var iframe = $('#player1')[0];
var player = $f(iframe);
var status = $('.status');
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function() {
  player.api("play");
});

var pauseButton = document.getElementById("pause-button");
pauseButton.addEventListener("click", function() {
  player.api("pause");
});
setTimeout(function () {
player.addEvent('ready', function() {
player.addEvent('playProgress', onPlayProgress);
});
});
function onPlayProgress(data, id) {
var Time = data.seconds; 
    if (Time >= '20') {
    $('.show--div-20sec').show();
    }
}
});

CSS :

.button {
  width: 48px;
  height: 48px;
  cursor: pointer;
}

.defs {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

iframe {
  float: left;
  width: 350px;
  height: 200px;
}

.buttons {
  padding: 1rem;
  background: #f06d06;
  float: left;
}

body {
  padding: 1rem;
}

.show--div-20sec {
  width: 100%;
  background: red;
  height: 80px;
  float: left;
  display: none;
}

I implemented all the required code tried all the other way around to target Vimeo video Iframe, The end target is to show a button once video is played for 20 seconds and failed to do.

Page where i integrated : https://walltomain.com/test/, Its a wordpress divi website.

make it constantly blinks / glows when mouse hovers over the image

I created an image animation using CSS and Javascript, and I would like to make it constantly blinks / glows (with the pink colour) when the mouse cursor hovers on the image. how should I change the code and using the javascript to achieve this?

Here is the source code that I’ve tried.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
  outline: 0;
  border: none;
}
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #22232e;
}
button {
  display: flex;
  justify-content: center;
  align-items: center;
  background: transparent;
  position: relative;
}
button .btn-img{
  padding: 10px 15px;
  font-size: 13px;
  text-align: center;
  color: #e0ffff;
  border: 2px solid rgba(255,255,255,0.1);
  border-radius: 15px;
  background: rgba(0,73,88,0.05);
  backdrop-filter: blur(15px);
  cursor: pointer;
  z-index: 1;
  transition: 0.2s;
}
button::before{
  content: '';
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: -3px;
  width: 25%;
  height: 10px;
  background: #00c2cb;
  border-radius: 10px;
  transition: .5s;
  box-shadow: 0 0 10px rgba(0,194,203,0.5);
}
button:hover::before{
  bottom: 0;
  height: 40%;
  width: 90%;
  border-radius: 30px;
  transition-delay: 0.5s;
  /* background: #ffbd1f; */
  background: #db0079;
}
<button>
  <span class="btn-img">
    <img src="https://img1.daumcdn.net/thumb/R48x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FtKZbq%2FbtsEb7zLet0%2FHDOJKKBGmhp3kWrFZXXTFk%2Fimg.png"></br><div id="tr" style="display: table-cell; text-align: center; color: rgb(255,255,255)";>Sample
  </span>
</button>

to see the demo, please take a look at the codepen.

thank you.

I’m trying to create unique editors for notes but I can’t

a few days ago I was programming a notes website but a problem arose and that is that there is only one value for the editors, I am using EditJs and I have tried everything but it hasn’t worked. Here is my component:

` const editorInstances = useRef<{ [key: string]: EditorJS | null }>({});
const editorRefs = useRef<{ [key: string]: React.RefObject }>({});
const [contents, setContents] = useState<{ [key: string]: any }>({});

const handleEditorChange = (noteId: string) => {
    return (api: any, event: BlockMutationEvent | BlockMutationEvent[]) => {
        api
            .save()
            .then((outputData: any) => {
                console.log("Article data: ", outputData);
                setContents(prevContents => ({
                    ...prevContents,
                    [noteId]: outputData
                }));
                localStorage.setItem(noteId, JSON.stringify(outputData));
            })
            .catch((error: any) => {
                console.log("Saving failed: ", error);
            });
    };
};

useEffect(() => {
    const storedContents: { [key: string]: any } = {};
    notes.forEach(note => {
        const storedData = JSON.parse(window.localStorage.getItem(note.idNote) || "{}");
        storedContents[note.idNote] = storedData;
    });
    setContents(storedContents);
}, [notes]);

useEffect(() => {
    const newEditorInstances: { [key: string]: EditorJS | null } = {};
    const newEditorRefs: { [key: string]: React.RefObject<HTMLDivElement> } = {};

    notes.forEach(note => {
        const config: EditorConfig = {
            holder: `editor-${note.idNote}`,
            onChange: handleEditorChange(note.idNote),
            tools: {
                header: {
                    class: Header,
                    inlineToolbar: true,
                },
                list: {
                    class: List,
                    inlineToolbar: true,
                },
                paragraph: {
                    class: Paragraph,
                    inlineToolbar: true,
                },
                image: {
                    class: ImageTool,
                    inlineToolbar: true,
                },
            },
        };

        newEditorInstances[note.idNote] = new EditorJS(config);
        newEditorRefs[note.idNote] = React.createRef();
    });

    editorInstances.current = newEditorInstances;
    editorRefs.current = newEditorRefs;

    return () => {
        Object.values(editorInstances.current).forEach(instance => {
            if (instance) {
                instance.destroy();
            }
        });
    };
}, [notes]);

useEffect(() => {
    Object.entries(editorInstances.current).forEach(([noteId, instance]) => {
        const content = contents[noteId];
        if (instance && content) {
            instance.isReady
                .then(() => {
                    instance?.render(content);
                })
                .catch((error) => {
                    console.error(error);
                });
        }
    });
}, [contents]);

return (
    <div>
        {notes.map(note => (
            <SectionNote key={note.idNote}>
                <TitleNote>{note.titleNote}</TitleNote>
                <OptionColors>
                    <TextArea id={`editor-${note.idNote}`} ref={editorRefs.current[note.idNote]} />
                </OptionColors>
            </SectionNote>
        ))}
    </div>
);`