after adding html blocks using ajax, animation(jquery) does not work

if you add this block forcibly, then everything works. my searches led me to the fact that when clicking on input, the focused is-focused classes are not added to it. 1 screenshot – how it works if you add html forcibly, 2 screenshot – how it works after loading using ajax
1
2

<html>
<div class="container-fluid py-4 contents">
    </div>
 <script src="../assets/js/core/popper.min.js"></script>
  <script src="../assets/js/core/bootstrap.min.js"></script>
    <script src="../assets/js/material-dashboard.min.js?v=3.1.0"></script>
  <script src="../assets/js/plugins/perfect-scrollbar.min.js"></script>
  <script src="../assets/js/plugins/smooth-scrollbar.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <script src="../assets/js/plugins/chartjs.min.js"></script>
      <!-- Github buttons -->
  <script async defer src="https://buttons.github.io/buttons.js"></script>

  <script>
async function Send_ajax(data,dataType,url){
   var result ="";
 try {
       
    $.ajax({
        url:url, //url  (action_ajax_form.php)
        type:"POST",
        async:false,
        data:data,  
        dataType: dataType, // 
        success:function(data){ 
        result = data;
},
        error: function(response) { // Данные не отправлены
           result= response;
        }
         
    });
   
  } catch(error) {
    // handle error, set some error state, display error toast, etc...
    result= error;
  }
  return result;
  }
  $(document).ready(function(){
    Send_ajax("","html","../php/admin/get_config_form.php").then((result) => {
     $(".contents").html(result)
     });
      });
</script>
</html>

Js calendar help does not switch month after december

I’m creating a calendar in JavaScript and encountering an issue with switching months. When I’m in December 2023, it doesn’t switch to January 2024 but only to December 2024. When moving forward, it only switches months, and the same occurs when moving backward. So, I believe the issue lies in this code:

prevMonthBtn.addEventListener("click", function () {
    currentMonth--;
    if (currentMonth < 0) {
        currentMonth = 11;
        currentYear--;
    }
    createCalendar(currentYear, currentMonth);
});

nextMonthBtn.addEventListener("click", function () {
    currentMonth++;
    if (currentMonth > 11) {
        currentMonth = 0;
        if (currentMonth === 0) {
            currentYear++;
        }
    }
    createCalendar(currentYear, currentMonth);
});

Here is my code

document.addEventListener('DOMContentLoaded', function () {
    const calendar = document.getElementById("calendar");
    let currentYear, currentMonth;
    const monthNames = [
        "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec",
        "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"
    ];
    const dayNames = ["Pn", "Wt", "Śr", "Czw", "Pt", "Sob", "Nie"];
    function createCalendar(year, month) {
        const today = new Date();
        currentYear = year || today.getFullYear();
        currentMonth = month || today.getMonth();
        const currentDay = today.getDate();
        const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
        const firstDay = new Date(currentYear, currentMonth, 1).getDay() || 7;
        calendar.innerHTML = "";
        const monthName = monthNames[currentMonth];
        calendar.innerHTML += `<div class="d-flex title-month">  
            <button id="prevMonth" class="prevMonth"><</button>
            <h2 class="nameOfMonth">${monthName} ${currentYear}</h2>
            <button id="nextMonth" class="nextMonth">></button></div>
        `;
        const table = document.createElement("table");
        let day = 1;
        const headerRow = document.createElement("tr");
        dayNames.forEach(function (dayName) {
            const th = document.createElement("th");
            th.textContent = dayName;
            headerRow.appendChild(th);
        });
        table.appendChild(headerRow);
        for (let i = 0; i < 6; i++) {
            const row = document.createElement("tr");
            for (let j = 0; j < 7; j++) {
                if (i === 0 && j < firstDay - 1) {
                    const cell = document.createElement("td");
                    row.appendChild(cell);
                } else if (day <= daysInMonth) {
                    const cell = document.createElement("td");
                    cell.textContent = day;
                    if (day === currentDay && currentMonth === today.getMonth() && currentYear === today.getFullYear()) {
                        cell.classList.add("today");
                    } else if (new Date(currentYear, currentMonth, day) < today) {
                        cell.classList.add("past");
                    }
                    if (j === 5 || j === 6) {
                        cell.classList.add("weekend");
                    }
                    row.appendChild(cell);
                    day++;
                    if (!(new Date(currentYear, currentMonth, day - 1) <= today)) {
                        cell.addEventListener("click", (event) => {
                            if (!event.target.classList.contains("past")) {
                                const selectedDay = event.target.textContent;
                                openPopup(selectedDay, currentMonth + 1, currentYear);
                            }
                        });
                    }
                }
            }
            table.appendChild(row);
        }
        calendar.appendChild(table);
        const prevMonthBtn = document.getElementById("prevMonth");
        const nextMonthBtn = document.getElementById("nextMonth");

        prevMonthBtn.addEventListener("click", function () {
            currentMonth--;
            if (currentMonth < 0) {
                currentMonth = 11;
                currentYear--;
            }
            createCalendar(currentYear, currentMonth);
        });
        nextMonthBtn.addEventListener("click", function () {
            currentMonth++;
            if (currentMonth > 11) {
                currentMonth = 0;
                if (currentMonth === 0) {
                    currentYear++;
                }
            }
            createCalendar(currentYear, currentMonth);
        });
        
        function openPopup(day, month, year) {
            const popup = document.createElement("div");
            popup.classList.add("popup");
            popup.innerHTML = `
            <form id="bookingForm" method="post" action="/saveBooking">
                <input type="hidden" name="selected_date" id="selected_date" value="${year}-${month}-${day}">
                <span class="close-button" onclick="closePopup()">X</span>
                <h3>${day}.${month}.${year}</h3>
                <select name="category">
                    <option value="category1">Категорія 1</option>
                    <option value="category2">Категорія 2</option>
                    <option value="category3">Категорія 3</option>
                </select>
                <select name="time">
                    <option value="08:00">08:00</option>
                    <option value="09:00">09:00</option>
                    <option value="10:00">10:00</option>
                    <option value="11:00">11:00</option>
                    <option value="12:00">12:00</option>
                    <option value="13:00">13:00</option>
                    <option value="14:00">14:00</option>
                    <option value="15:00">15:00</option>
                    <option value="16:00">16:00</option>
                </select>
                <button type="submit" name="submit">Записатися</button>
            </form>
            `;
            document.body.appendChild(popup);
            const closeBtn = popup.querySelector(".close-button");
            closeBtn.addEventListener("click", function () {
                closePopup();
            });
        }

        function closePopup() {
            const popup = document.querySelector(".popup");
            if (popup) {
                popup.remove();
            }
        }
    }
    createCalendar();
});

How to show hidden menus in breadcrumb component?

I’m developing a breadcrumb component, one of the rules of the component is that if I have many items in the menu, I should only show the 1st, penultimate and last one menu. The rest of the menus must be hidden using the ellipsis symbol.

What I need to do is when I click on the ellipsis symbol it should open a small window/modal where it shows the hidden menus.

It’s easier to understand with the image:

enter image description here
enter image description here

Can you tell me how to do this?

Here’s my code I put into codesandbox.io

import React from "react";
import { css } from "emotion";
import { ThemeConstants } from "./constants";
import Button from "./Button";
import Arrow from "./Arrow";

const { useState, useCallback } = React;

function Breadcrumb(props) {
  const { items, maxVisible } = props;
  const [isHovered, setIsHovered] = useState(false);
  const _items = items.slice();

  const handleHover = useCallback(() => setIsHovered(!isHovered), [isHovered]);

  const splitItemsAt =
    _items.length - maxVisible > 0 ? _items.length - maxVisible : 0;
  const overflowItems = _items.splice(0, splitItemsAt);
  
  const lastItem = _items.pop();

  const styles = getStyles();
  return (
    <div className={styles.box}>
      <Button label="My Files" shrink="0" />
      <OverflowItems items={overflowItems} type={props.type} />
      {_items.map((item, i) => {
        return [
          <Arrow key={`arrow-${i}`} type={props.type} />,
          <Button
            key={`btn-${i}`}
            label={item.label}
            shrink={isHovered ? 0.0001 : 25}
            onMouseOver={handleHover}
            onMouseOut={handleHover}
          />
        ];
      })}

      <Arrow type={props.type} />
      <Button label={lastItem.label} shrink={isHovered ? 0.0001 : 10} />
    </div>
  );
}

function OverflowItems(props) {
  const { items } = props;
  return items.length ? (
    <>
      <Arrow type={props.type} />
      <Button label="..." shrink="0" />
    </>
  ) : null;
}

function getStyles() {
  return {
    box: css`
      border: 1px solid ${ThemeConstants.colors.n60};
      padding: 16px;
      flex: 1 1 auto;
      flex-direction: row;
      display: flex;
      align-items: center;
      min-width: 0;
      overflow: hidden;
      transition: flex-shrink 500ms ease-in-out;
      &:hover {
        flex-shrink: 0.0001;
      }
    `
  };
}
export default Breadcrumb;

Gutenberg Api-Fetch to Database

I’m new with Gutenberg / WP and i’m trying to send data to database with my form block. I created a “subscribers” table on the database with this fn:

function register_subscribers_table() {

    //Connect to database
    global $wpdb;

    //Table name
    $table_name = $wpdb->prefix . 'subscribers';

    //Access character set and collation for the database
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        name tinytext NOT NULL,
        email varchar(100) NOT NULL,
        PRIMARY KEY  (id)
     ) $charset_collate;";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );

}
add_action( 'init', 'register_subscribers_table' );

This code in my php file of plugin.

And i’m trying to send form data (email) to the database with javascript & React in my block scripts (view.js in block):

 const form = document.querySelectorAll(".my-form");

    Array.from(form).forEach(function(el){

    el.addEventListener("submit", function(event){
      event.preventDefault();

      const data = new FormData(event.target);
      const result = data.get("email");

      // I need send the result to the database

      el.reset();
      })
    
    })

I tried api-fetch but i can reach the posts/pages only, no database. Is there a way to do it?

responsive web design using html css js

I’ve designed a website, but it doesn’t look good on mobile devices. What are some strategies for making a website more mobile-friendly? Are there CSS frameworks or techniques that can help with responsive design.
I’ve tried using media queries to adjust the styling based on the screen size. However, I’m not sure if I’m implementing them correctly.

When I run scrollintoview in Safari, the element disappears from the screen

I am currently developing in the next.js environment.

useEffect(() => {
  topCardRef.current?.scrollIntoView();
}, [data]);

As in the code above, it was implemented to scroll when there is a change in data.

In Chrome, it works as expected, but in Safari, the scrolling element is not displayed on the screen after the function is executed.

Elements that disappear from the screen appear again when the user scrolls.

Did I give you the wrong options?

I would like to know how to prevent elements from disappearing from the screen after running scrollintoview.

How to make useStore detect state change?

It renders a button changing store.a.state.

When I click a button it executes that method and I can check it by console.log.

At the same time I expect the button content is changed to “b”, but it remains intact.

What am I missing here?

(noSerialize is required, because it is simplified form of complex code)

import type { NoSerialize } from "@builder.io/qwik";
import {
  component$,
  noSerialize,
  useStore,
  useVisibleTask$,
} from "@builder.io/qwik";
import { css } from "~/styled-system/css";
import { Container } from "~/styled-system/jsx/container";

export default component$(() => {
  const store = useStore<{
    a: NoSerialize<{ state: "a" | "b"; toggle: () => void }> | null;
  }>({ a: null });

  useVisibleTask$(async () => {
    store.a = noSerialize({
      state: "a" as "a" | "b",
      toggle() {
        this.state = this.state === "a" ? "b" : "a";
        console.log(`a.toggle invoked`, this);
      },
    });
  });

  return (
    <Container
      class={css({ display: "flex", flexFlow: "column nowrap", gap: "4" })}
    >
      <button
        class={css({
          rounded: "lg",
          backgroundColor: "green.600",
          cursor: "pointer",
          color: "white",
          padding: "1",
          _hover: { backgroundColor: "green.500" },
          _active: { backgroundColor: "green.400" },
        })}
        onClick$={() => store.a?.toggle()}
      >
        {store.a?.state}
      </button>
    </Container>
  );
});

Value of dropdown not showing after reload

on my website you can choose your city, province and region. Once you choose the region you can now select the province after province you can now select for city. ONce i save the info and reload the page the data or the one i choose on the dropdown of city and province is not showing

the saved data is showing on the database but the data is not showing in the website once you reload it

How to use the function in Javascript [closed]

How to add function in javascript like min, max, pow,etc.If anyone know how to implement it and where it can implement it?

How to add function in javascript like min, max, pow,etc.If anyone know how to implement it and where it can implement it.I except that it can provide some knowledge about function of Javascript.

Repository in Git and Github

If you are given an array of integers. Write a function that finds and returns the two numbers in the array that sum up to a specific target. If no such pair is found, the function should return an empty array.

I need explanation for this question as my faculty gave this question without explaining the concept.

patna@Teja_ENVY MINGW64 /d/GIT PORTFOLIO (master)
$ ^C

patna@Teja_ENVY MINGW64 /d/GIT PORTFOLIO (master)`

patna@Teja_ENVY MINGW64 /d/GIT PORTFOLIO (master)
$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file:   GIT repo.txt.txt
        new file:   repository.txt.txt

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   repository.txt.txt


patna@Teja_ENVY MINGW64 /d/GIT PORTFOLIO (master)
$ git add .

patna@Teja_ENVY MINGW64 /d/GIT PORTFOLIO (master)
$ git commit -m "version-1"
[master (root-commit) 4c1fd34] version-1
 2 files changed, 3 insertions(+)
 create mode 100644 GIT repo.txt.txt
 create mode 100644 repository.txt.txt

patna@Teja_ENVY MINGW64 /d/GIT PORTFOLIO (master)
$ git log
commit 4c1fd34ed836788c4890bc61d51a2bb63de5ade4 (HEAD -> master)
Author: Hari <[email protected]>
Date:   Sun Dec 3 12:17:46 2023 +053

    version-1

patna@Teja_ENVY MINGW64 /d/GIT PORTFOLIO (master)
$ ^C

patna@Teja_ENVY MINGW64 /d/GIT PORTFOLIO (master)

Access Gradio API with pure JS

Is there a way I can access- the API of a Hugging Face Space build with Gradio with pure js, instead of having to install the gradio client package and use node js.

I’ve tried sending post request to the expected endpoint, but it returns a 500 error.

What is the significance of the ‘this’ keyword in JavaScript?

The closure closureInstance retains a reference to the hugeData array, preventing it from being garbage-collected even after the closureMemoryLeak function execution ends. This can lead to memory leaks, especially if large amounts of data are captured and held unnecessarily.

Line 2: closureMemoryLeak function starts.
Line 3: Creates a large array hugeData with a million ‘someData’ elements.
Line 4-6: Defines a closure closure that logs the length of hugeData.
Line 9: Invokes closureInstance.

How to increment key property of an object

Let’s say I have the following objects:

[
 {
    "1": "Word1_1",
    "2": "Word2_1"
    "3": "Word3_1"
 },
 {
    "1": "Word1_2",
    "2": "Word2_2"
    "3": "Word3_2"
 },
 {
    "1": "Word1_3",
    "2": "Word2_3"
    "3": "Word3_3"
 }
]

and I want to iterate only through the keys of 1s (which is string) to print:
Wrod1_1, Word1_2, Word1_3
and then increment the key by one to print values of key 2s: Wrod2_1, Word2_2, Word2_3.

rendering problem inside a react application

I’ve built a react app in which I’m fetching api data and displaying on UI, in each row I’m adding editing and deleting the row data locally (not overwriting the real data from API, just in local storage). Editing is inline functionality.
My node version is 18.12.1 and npm version is 10.2.3
here is my app.js file:

import React, { useState, useEffect } from 'react';
import Table from './table';
import './App.css';
import axios from 'axios';
//import { AppStateProvider } from './AppStateContext';

const API_ENDPOINT = 'https://geektrust.s3-ap-southeast-1.amazonaws.com/adminui-problem/members.json';

const App = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    // Fetch data from the API
    async function fun() {
      const res = await axios.get(API_ENDPOINT);
      setData(res.data);
    }
    fun();
  }, []);

  return (
    <div>
      <Table data={data} />
    </div>
  );
};

export default App;

here is table.js component:

import React, { useState, useEffect } from 'react';
import TableRow from './tableRow';
import './table.css';

const Table = ({ data }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedRows, setSelectedRows] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [isEditing, setEditing] = useState(false);
  const [editedRowData, setEditedRowData] = useState({});
  const rowsPerPage = 5;

  // Use the data state to manage the original data
  const [visibleData, setVisibleData] = useState(data);

  useEffect(() => {
    const filteredData = data
      .filter(row =>
        Object.values(row).some(value =>
          value.toString().toLowerCase().includes(searchTerm.toLowerCase())
        )
      );
    setVisibleData(filteredData.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage));
  }, [data, searchTerm, currentPage, rowsPerPage]);

  const totalPages = Math.ceil(data.length / rowsPerPage);
  const paginationButtons = Array.from({ length: totalPages }, (_, index) => index + 1);

  const handleEdit = (editedRow) => {
    setEditedRowData(editedRow);
    setEditing(true);
  };

  const handleSave = () => {
    // Update the data state to reflect changes
    const updatedData = data.map(row => (row.id === editedRowData.id ? editedRowData : row));

    // Update the visibleData state to reflect changes and pagination
    setVisibleData(updatedData.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage));

    setEditing(false);
  };

  const handleDelete = () => {
    // Update the data state to reflect changes
    const updatedData = data.filter(row => !selectedRows.includes(row.id));

    // Update the visibleData state to reflect changes and pagination
    setVisibleData(updatedData.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage));
    setSelectedRows([]);
  };

  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  const handleToggleAllRows = () => {
    const allRows = visibleData.map(row => row.id);
    if (selectedRows.length === allRows.length) {
      setSelectedRows([]);
    } else {
      setSelectedRows(allRows);
    }
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <table>
        <thead>
          <tr>
            <th>
              <input
                type="checkbox"
                checked={selectedRows.length === visibleData.length}
                onChange={handleToggleAllRows}
              />
            </th>
            {Object.keys(data[0] || {}).map((column) => (
              <th key={column}>{column}</th>
            ))}
            <th>Edit</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          {visibleData.map((row) => (
            <TableRow
              key={row.id}
              row={row}
              selectedRows={selectedRows}
              setSelectedRows={setSelectedRows}
              isEditing={isEditing}
              onEdit={handleEdit}
              onSave={handleSave}
            />
          ))}
        </tbody>
      </table>
      <div className="pagination">
        {paginationButtons.map((button) => (
          <button
            key={button}
            onClick={() => handlePageChange(button)}
            className={button === currentPage ? 'active' : ''}
          >
            {button}
          </button>
        ))}
      </div>
      <button className="delete-selected" onClick={handleDelete}>
        Delete Selected
      </button>
    </div>
  );
};

export default Table;

and this is tableRow.js:-

import React, { useState } from 'react';

const TableRow = ({ row, selectedRows, setSelectedRows, isEditing, onEdit, onSave }) => {
  const [editedValues, setEditedValues] = useState({ ...row });
  const isSelected = selectedRows.includes(row.id);

  const handleEdit = (tempRow) => {
    onEdit(tempRow);
  };

  const handleSave = () => {
    onSave();
  };

  const handleToggleRow = () => {
    setSelectedRows(prevSelectedRows => {
      if (prevSelectedRows.includes(row.id)) {
        return prevSelectedRows.filter(id => id !== row.id);
      } else {
        return [...prevSelectedRows, row.id];
      }
    });
  };

  const handleChange = (column, value) => {
    setEditedValues(prevEditedValues => ({
      ...prevEditedValues,
      [column]: value,
    }));
    console.log("edited values:",editedValues);
  };

  return (
    <tr className={isSelected ? 'selected' : ''}>
      <td>
        <input
          type="checkbox"
          checked={isSelected}
          onChange={handleToggleRow}
        />
      </td>
      {Object.keys(row).map(column => (
        <td key={column}>
          {isEditing ? (
            <input
              type="text"
              value={editedValues[column]}
              onChange={(e) => handleChange(column, e.target.value)}
            />
          ) : (
            row[column]
          )}
        </td>
      ))}
      <td>
        {isEditing ? (
          <button onClick={() => handleSave(editedValues)}>Save</button>
        ) : (
          <button onClick={() => handleEdit(editedValues)}>Edit</button>
        )}
      </td>
      <td>
        {!isEditing ? (
          <button className="delete" onClick={() => setSelectedRows([row.id])}>
            Delete
          </button>
        ) : null}
      </td>
    </tr>
  );
};

export default TableRow;

can someone help me fix this issue? I’m not getting why is this happening?

Upon clicking edit button getting an editable row and upon saving the edited row it should reflect on the UI. But here I need to click twice on edit and save to get what I wanted. like once goto edit, change data and save, again open edit and save, and then only the changes are reflected on UI. I’m not getting why I need to save it twice to get the reflected changes. Also on refreshing the page the original data from API should display and i.e. working fine in my app.

I’ve tried using chatGPT but couldn’t solve the problem.