Does anyone know why the html duplicates when im searching?

Im doing a searcher page where i place an input and acording to the data in the input, it search in the database for similar articles and displays in the boxes. but when i search something another header and input appears in the page. duplicated header and input
Ive tried asking chatgpt but it couldnt help me. I also searched but couldnt find anything similar.

<?php
session_start();
if ($_SESSION["user"] == "" || $_SESSION["premium"] == "") {
    header("Location: index.php");
    exit();
}

$valorInput = isset($_GET["valor"]) ? $_GET["valor"] : "";

include "dbconnect.php";

$resultados = array();

if (!empty($valorInput)) {
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $stmt = $conn->prepare("SELECT name, description, link, imagelink, price FROM Articulos WHERE description LIKE ?");
        $param = "%$valorInput%";
        $stmt->bind_param("s", $param);
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $resultados[] = '<div class="template">
                <img src="' . $row['imagelink'] . '" alt="' . $row['description'] . '">
                <p>' . $row['name'] . '</p>
                <p>' . $row['description'] . '</p>
                <p>Precio: ' . $row['price'] . '</p>
            </div>';
        }

        $stmt->close();
        echo implode('', $resultados);
        exit();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/inicio.css">
    <title>Buscador de Productos</title>
</head>
<body>

    <header>    
        <h1>Buscador de Productos</h1>
    </header>

    <div id="search-container">
        <input type="text" id="search-box" oninput="actualizarVariable()" placeholder="Buscar productos...">
        <div id="search-results" class="search-results-container"></div>
    </div>

    <div id="result-container" class="container">
        <?php 
        for($i = 0; $i < 6; $i++) {
            echo '<div class="template">
            <img src="imagen1.jpg" alt="';
            echo $valorInput;
            echo '">
            <p>Descripción del Producto 1</p>
            </div>';
        }
        ?>
    </div>

    <script>
        function actualizarVariable() {
            var valorInput = document.getElementById("search-box").value;
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("result-container").innerHTML = this.responseText;
                }
            };
            xhttp.open("GET", "inicio.php?valor=" + valorInput, true);
            xhttp.send();
        }
    </script>
    <script src="script.js"></script>
</body>
</html>

I would like to import pixi.js as a module in a vanilla JS project, yet I cannot

File structure:

  • index.html
  • main.js
  • pixi.js

My index.html:

<!doctype html>
<html>
  <head>
    <style>
        body{
            margin: 0px;
            overflow: hidden;
        }
    </style>
    <script src="main.js" type="module" defer></script>
  </head>
  <body>
    
  </body>
  </html>

main.js:

import * as PIXI from './pixi.js';
const app = new PIXI.Application({ 
    resizeTo:window,
    antialias: true,
    autoDensity: true,
    resolution: 2 });
  document.body.appendChild(app.view);

Error: Uncaught TypeError: PIXI.Application is not a constructor

Other solutions tried:
This works properly when I import as a script tag e.g. <script src="pixi.js" type="module"></script> in index.html and then remove my import statement in main.js. A major downside of this approach is that I want to use JSDoc with linting, and under this method of importing it will not recognize PIXI as a valid type despite it being valid.
Another solution is to use a jsbundler and import * as PIXI from 'pixi.js', but this approach requires… a bundler. Can I just import it vanilla without extra tools?

How can I make sure that input date format does not change with browser language? [duplicate]

I am working on a website where some users have an American date format (mm/dd/yyyy) and others have a French one (dd/mm/aaaa), and maybe others have other formats (e.g. yyyy/mm/dd). Is there a way I can force an HTML input to have a specific date format? Or am I stuck with using <input type="text">?

Something like this
<input type="date" format='dd-mm-yyyy'>

I tried using placeholder="dd-mm-yyyy" but it did not work

finding mutated field value

here is my javascript code:

let tbody = document.querySelector('#tbody');
                                        let addBtn = document.querySelector('#addBtn');
                                        let IdString = "tablerow";
                                        let i = 4;
                                        function creatTableEl(id, pname, pweight, pprice) {
                                            const createTR = document.createElement("tr");
                                            createTR.setAttribute("id", id);
                                            tbody.appendChild(createTR);
                                            const createTD1 = document.createElement("td");
                                            const createTD2 = document.createElement("td");
                                            const createTD3 = document.createElement("td");
                                            const createTD4 = document.createElement("td");
                                            createTR.append(createTD1, createTD2, createTD3, createTD4);
                                            const createInputField1 = document.createElement("input");
                                            createTD1.appendChild(createInputField1);
                                            createInputField1.setAttribute("type", "text");
                                            createInputField1.setAttribute('id', pname);
                                            const createInputField2 = document.createElement("input");
                                            createTD2.appendChild(createInputField2);
                                            createInputField2.setAttribute("type", "text");
                                            createInputField2.setAttribute('id', pweight);
                                            const createInputField3 = document.createElement("input");
                                            createTD3.appendChild(createInputField3);
                                            createInputField3.setAttribute("type", "number");
                                            createInputField3.setAttribute("id", pprice);
                                            createTD4.setAttribute("id", "Delete");
                                            createTD4.innerHTML = "&#10006";
                                            createTD4.addEventListener("click", DeleteCells);
                                            function DeleteCells() {
                                                const deleteCellIDs = createTR.getAttribute("id");
                                                createTR.remove(deleteCellIDs);
                                            }
                                            return createTR;
                                        }
                                        function addTableRowBtn() {
                                            let id = IdString + i;
                                            let pname = 'pname' + i;
                                            let pweight = 'pweight' + i;
                                            let pprice = 'pprice' + i;
                                            i++;
                                            const tableEle = creatTableEl(id, pname, pweight, pprice);
                                            tbody.insertBefore(tableEle, addBtn);
                                        }
                                        function Table() {
                                            for (let y = 0; y < 4; y++) {
                                                let id = IdString + y; let pname = 'pname' + y; let
                                                    pweight = 'pweight' + y; let pprice = 'pprice' + y; const
                                                        constTableEle = creatTableEl(id, pname, pweight, pprice); 
                                                tbody.insertBefore(constTableEle, addBtn);
                                            } addBtn.addEventListener("click",
                                                addTableRowBtn);
                                        } Table(); 

how can i get the pprice, pweight, pname value in an array

I cannot get input field value form javascript. because the input fields are created dynamically by javascript. and mutationOvserver object i try to use. but i failed. i cannot type the proper code for these issue. what can i do? Please help me.

How make smth like (screen) using CSS [closed]

I’m currently working on a personal project and facing difficulties in implementing a text block according to a design I have in mind. I have a screen
here it is

illustrating the desired appearance of the text block.My current attempt is not yielding the expected results.

Sooo… how can i do this?

Any advice, code snippets, or insights would be greatly appreciated. Thank you for your time and assistance!

How to create a button that generates a pdf file of everything in the page in React.js

import React, { useState, useRef } from 'react';
import Modal from 'react-modal';
import './App.css';

function App() {
  const [scenarios, setScenarios] = useState([]);
  const [images, setImages] = useState([]);
  const [editing, setEditing] = useState(null);
  const [modalIsOpen, setModalIsOpen] = useState(false);

  const [title, setTitle] = useState('Titulo: ');
  const [given, setGiven] = useState('Dado que ');
  const [when, setWhen] = useState('Quando ');
  const [and, setAnd] = useState('E ');
  const [then, setThen] = useState('Então ');

  const inputRef = useRef([]);

  const openModal = () => {
    setTitle(`CT${scenarios.length + 1}: `);
    setModalIsOpen(true);
  };

  const closeModal = () => {
    setModalIsOpen(false);
  };

  const handleImageUpload = (e) => {
    const files = Array.from(e.target.files);
    const newImages = files.map(file => URL.createObjectURL(file));
    setImages(oldImages => [...oldImages, ...newImages]);
  };

  const handleAddScenario = () => {
    if (given.trim() === '' || when.trim() === '' || and.trim() === '' || then.trim() === '') {
      alert('Please fill in all the textareas.');
      return;
    }
  
    const scenario = {
      title,
      given,
      when,
      and,
      then,
      images,
    };
  
    if (editing !== null) {
      const newScenarios = [...scenarios];
      newScenarios[editing] = scenario;
      setScenarios(newScenarios);
      setEditing(null);
    } else {
      setScenarios(oldScenarios => [...oldScenarios, scenario]);
      setTitle(`CT ${scenarios.length + 2}: `);
    }
    setGiven('Dado que ');
    setWhen('Quando ');
    setAnd('E ');
    setThen('Então ');
    setImages([]);
    setModalIsOpen(false);
  };

  const handleTextChange = (e, index, field) => {
    const text = e.target.value;
    const newScenarios = [...scenarios];
  
    if (index >= 0 && index < newScenarios.length) {
      newScenarios[index][field] = text;
      setScenarios(newScenarios);
    } else {
      console.error(`Invalid index: ${index}`);
    }
  };

  const handleRemoveImage = (scenarioIndex, imageIndex) => {
    const newScenarios = [...scenarios];
    newScenarios[scenarioIndex].images.splice(imageIndex, 1);
    setScenarios(newScenarios);
  };

  const handleImageChange = (e, scenarioIndex, imageIndex) => {
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.onloadend = () => {
      const newScenarios = [...scenarios];
      newScenarios[scenarioIndex].images[imageIndex] = reader.result;
      setScenarios(newScenarios);
    };
    reader.readAsDataURL(file);
  };

  const handleRemoveScenario = (index) => {
    const newScenarios = [...scenarios];
    newScenarios.splice(index, 1);
    setScenarios(newScenarios);
  };

 
  return (
    
    <div className="App">
      
      <Modal
        isOpen={modalIsOpen}
        onRequestClose={closeModal}
        contentLabel="Create Scenario"
      >
        <textarea 
          value={title} 
          onChange={e => setTitle(e.target.value)} 
        />
        <textarea 
          value={given} 
          onChange={e => setGiven(e.target.value)} 
        />
        <textarea 
          value={when} 
          onChange={e => setWhen(e.target.value)} 
        />
        <textarea 
          value={and} 
          onChange={e => setAnd(e.target.value)} 
        />
        <textarea 
          value={then} 
          onChange={e => setThen(e.target.value)} 
        />
        <label htmlFor="fileUpload" className="fileUpload"> Importar Imagens
          <input id="fileUpload" type="file" onChange={handleImageUpload} multiple />
        </label>
        <button onClick={handleAddScenario}><i class="fas fa-plus"></i>Add Scenario</button>
        <button onClick={closeModal}><i class="fas fa-times"></i>Close</button>
      </Modal>
      
      {scenarios.map((scenario, index) => (
      <div key={index}>
        <div className = "hover-container">
          <div className="hover-button">
            <button onClick={() => handleRemoveScenario(index)}>Remove Scenario {index+1}</button>
          </div>
              
          <textarea 
            value={scenario.title} 
            onChange={e => handleTextChange(e, index, 'title')} 
            style={{
              width: '100%',
              minHeight: '5px',
              border: '1px solid #ccc',
              borderRadius: '4px',
              padding: '10px'
            }}
          />
          <textarea 
            value={scenario.given} 
            onChange={e => handleTextChange(e, index, 'given')} 
            style={{
              width: '100%',
              minHeight: '5px',
              border: '1px solid #ccc',
              borderRadius: '4px',
              padding: '10px'
            }}
          />
          <textarea 
            value={scenario.when} 
            onChange={e => handleTextChange(e, index, 'when')} 
            style={{
              width: '100%',
              minHeight: '5px',
              border: '1px solid #ccc',
              borderRadius: '4px',
              padding: '10px'
            }}
          />
          <textarea 
            value={scenario.and} 
            onChange={e => handleTextChange(e, index, 'and')} 
            style={{
              width: '100%',
              minHeight: '5px',
              border: '1px solid #ccc',
              borderRadius: '4px',
              padding: '10px'
            }}
          />
          <textarea 
            value={scenario.then} 
            onChange={e => handleTextChange(e, index, 'then')} 
            style={{
              width: '100%',
              minHeight: '5px',
              border: '1px solid #ccc',
              borderRadius: '4px',
              padding: '10px'
            }}
          />
        </div> 
        {scenario.images.map((image, imageIndex) => (
          <div key={imageIndex} className="image-container">
          <img src={image} alt="" />
          <div className="image-buttons">
            <button onClick={() => handleRemoveImage(index, imageIndex)}>
              <i className="fa fa-trash"></i>
            </button>
            <input type="file" style={{display: 'none'}} ref={input => inputRef.current[imageIndex] = input} onChange={e => handleImageChange(e, index, imageIndex)} />
            <button onClick={() => inputRef.current[imageIndex].click()}>
              <i className="fa fa-pencil-alt"></i>
            </button>
          </div>
        </div>
        ))}
      </div>
    ))}
    <button onClick={openModal}>Create Scenario</button>
    </div>
  );
}

export default App;

This code, creates scenarios, where you need to fill all the necessary information and add images(if you want too), and then add this informations to the page as an div, you can create multiple of then, remove images, change undesired images, etc.

Given this code, I want to create a button that converts the entire page into a dynamic pdf, with all the scenarios and images displayed, remove the buttons and turn the textareas in to normal text when printed.

You can use any mehtod that acheives that result, i’ve tried jspdf, html2canvas and even file-saver, but they didn’t work all that well.

I feel like i tried everthing but nothing worked. Either they didn’t show anything in the pdf or add multiple not needed pages, wrong placement of the elements in the pdf, an a lot of other problems.

How can I make something like that?

Unable to convert PDF file to uint8Array

I am unable to convert a PDF file to uint8, which I get as a response to an API request. When printing out the response in the console, it has this form:

%PDF-1.4
%����
1 0 obj
<</CreationDate(D:20231025135518+02'00')/Creator( ... >>
endobj
2 0 obj
...

I am trying to display the PDF I get as a response, in a new browser tab. The snippet of code I use to convert and display this response looks like this:

let response = await this.getDocument(id);
if(response.status === 200){
    let responseText = await response.text();
    let uint8Array = new Uint8Array(responseText.length);
    for (let i = 0; i < responseText.length; i++) {
        uint8Array[i] = responseText.charCodeAt(i);
    }
    var file = new Blob([uint8Array], { type: 'application/pdf' });
    var fileURL = URL.createObjectURL(file);
    window.open(fileURL);
}

When I run this code, a new browser tab opens, the pdf it displays is empty however. When running the same request with Postman, I am getting the same response, only that Postman is able to display the correct PDF instead of a blank one. Running console.log(responseText); prints out the previously stated response, which is the same as the one I get in Postman.

At this point, I should add that this code is part of a Lightning Web Component, I am trying to develop on Salesforce, in case a valid answer does not work.

I have been trying to figure out how to solve this issue for a while, so any help or pointers are appreciated.

How can be rewritten the vanilla JavaScript onchange select input event code to OOP JavaScript?

The initial code is a vanilla js function which listens to change event handler of a select tag. By selecting a specific option inside the select, using the Switch js case, a special logic is initiated, basically this logic is setting an empty string, or an array, or anything else. So I wonder if there is a way to rewrite the logic to OOP JavaScript classes. I assum
e ther’s no need to rewrite every function… mainly to help me see thebasic logic architecture. Thank you

<script>
    // init variables
    const formSelect = document.querySelector('.form-select')
    const fromInput = document.querySelector('.from-input')
    const toInput = document.querySelector('.to-input') 
    const textFieldFrom = document.querySelector('.text-field-from')
    const textFieldTo = document.querySelector('.text-field-to')
    
    // init state
    let fromInputValue = ''
    let toInputValue = ''
    let range = []
    
    function setAllFieldsHidden() {
        toInput.style.display = 'none';
        textFieldFrom.style.display = 'none';
        textFieldTo.style.display = 'none';
        fromInput.style.display = 'none';
    }
    
    function setSingleDateFieldBlock() {
        toInput.style.display = 'none';
        textFieldFrom.style.display = 'none';
        textFieldTo.style.display = 'none';
        fromInput.style.display = 'block';
    }
    function setAllDateFieldsBlock() {
        textFieldFrom.style.display = 'none';
        textFieldTo.style.display = 'none';
        fromInput.style.display = 'block';
        toInput.style.display = 'block';
    }
    
    function setSingeTextFieldBlock() {
        fromInput.style.display = 'none';
        toInput.style.display = 'none';
        textFieldTo.style.display = 'none';
        textFieldFrom.style.display = 'block';
    }
    function setAllTextFieldsBlock() {
        fromInput.style.display = 'none';
        toInput.style.display = 'none';
        textFieldFrom.style.display = 'block';
        textFieldTo.style.display = 'block';
    }
  
    formSelect.addEventListener("change", function() {

        let selectedOption = formSelect.options[formSelect.selectedIndex].value;


        switch(formSelect.value) {
            case 'yesterday':
                setAllFieldsHidden();
                let currentDateY = new Date()
                let yesterdayD = new getDate(currentDateY)
                yesterdayD.setDate(yesterdayD.getDate() - 1)
                formSelect.value = yesterdayD

                break

            case 'today':
                setAllFieldsHidden();
                formSelect.value = new Date().getDate()
                break

            case 'tomorrow':
                setAllFieldsHidden();

                let currentDateT = new Date()
                let yesterday = new getDate(currentDateT)
                yesterday.setDate(yesterday.getDate() + 1)
                formSelect.value = yesterday
                break

            case 'recentWeek':
                setAllFieldsHidden();

                let todayR = new Date();
                let currentDayOfWeek = today.getDay();
                let diff = today.getDate() - currentDayOfWeek;
                let recentWeekDates = [];
                for (let i = 1; i < 8; i++) {
                    let tempDate = new Date(todayR);
                    tempDate.setDate(diff + i);
                    recentWeekDates.push(tempDate);
                }
                formSelect.value = recentWeekDates
                break

                case 'previousWeek':
                    setAllFieldsHidden();

                    let todayP = new Date();
                    let startOfPreviousWeek = new Date(todayP);
                    startOfPreviousWeek.setDate(startOfPreviousWeek.getDate() - 7);
                    let previousWeekDates = [];
                    for (let i = 0; i < 7; i++) {
                        let tempDate = new Date(startOfPreviousWeek);
                        tempDate.setDate(startOfPreviousWeek.getDate() + i);
                        previousWeekDates.push(tempDate);
                    }
                    formSelect.value = previousWeekDates
                    break

                case 'recentMonth':
                    setAllFieldsHidden();

                    let todayM = new Date();
                    todayM.setDate(1);
                    let recentMonthDates = [];
                    while (todayM.getMonth() === new Date().getMonth()) {
                    recentMonthDates.push(new Date(todayM));
                    todayM.setDate(todayM.getDate() + 1);
                    }
                    formSelect.value = recentWeekDates
                    break

                case 'previousMonth':
                    setAllFieldsHidden();

                    let todayPm = new Date();
                    let firstDayOfCurrentMonth = new Date(today.getFullYear(), todayPm.getMonth(), 1);
                    let lastDayOfPreviousMonth = new Date(firstDayOfCurrentMonth);
                    lastDayOfPreviousMonth.setDate(0);
                    let previousMonthDates = [];
                    for (let i = 1; i <= lastDayOfPreviousMonth.getDate(); i++) {
                    let tempDate = new Date(lastDayOfPreviousMonth);
                    tempDate.setDate(i);
                    previousMonthDates.push(tempDate);
                    }
                    formSelect.value = previousMonthDates
                    break

                case 'recentQuarter':
                    setAllFieldsHidden();

                    let todayRq = new Date();
                    let currentYear = todayRq.getFullYear();
                    let currentMonth = todayRq.getMonth();
                    let currentQuarter = Math.floor(currentMonth / 3) + 1;
                    let startDate = new Date(currentYear, (currentQuarter - 1) * 3, 1);
                    let endDate = new Date(currentYear, currentQuarter * 3, 0);
                    let actualQuarterDates = [];
                    for (let date = new Date(startDate); date <= endDate; date.setDate(date.getDate() + 1)) {
                        actualQuarterDates.push(new Date(date));
                    }
                    formSelect.value = recentWeekDates
                    break

                case 'last7Days':
                    setAllFieldsHidden();

                    let todayLse = new Date();
                    let lastSevenDaysDates = [];
                    for (let i = 6; i >= 0; i--) {
                        let tempDate = new Date(todayLse);
                        tempDate.setDate(today.getDate() - i);
                        lastSevenDaysDates.push(tempDate);
                    }
                    formSelect.value = lastSevenDaysDates
                    break

                case 'last30Days':
                    setAllFieldsHidden();

                    let todayLt = new Date();
                    let lastThirtyDaysDates = [];
                    for (let i = 29; i >= 0; i--) {
                        let tempDate = new Date(todayLt);
                        tempDate.setDate(today.getDate() - i);
                        lastThirtyDaysDates.push(tempDate);
                    }
                    formSelect.value = lastThirtyDaysDates
                    break

                case 'last60Days':
                    setAllFieldsHidden();

                    let todayLs = new Date();
                    let lastSixtyDaysDates = [];
                    for (let i = 59; i >= 0; i--) {
                        let tempDate = new Date(todayLs);
                        tempDate.setDate(todayLs.getDate() - i);
                        lastSixtyDaysDates.push(tempDate);
                    }
                    formSelect.value = lastDaysDates
                    break

                case 'last90Days':
                    setAllFieldsHidden();

                    let todayLn = new Date();
                    let lastNinetyDaysDates = [];
                    for (let i = 89; i >= 0; i--) {
                        let tempDate = new Date(todayLn);
                        tempDate.setDate(today.getDate() - i);
                        lastNinetyDaysDates.push(tempDate);
                    }
                    formSelect.value = lastNinetyDaysDates
                    break

                case 'lastNumberOfDays':
                    setSingeTextFieldBlock();

                    textFieldFrom.addEventListener("change", event => {
                        fromInputValue = event.target.value

                        for (let i = 0; i < fromInputValue; i++) {
                            let previousDate = new Date(currentDate);
                            previousDate.setDate(currentDate.getDate() - i);
                            range.push(previousDate);
                        }
                        range.reverse();
                    })
                    break

                case 'nextNumberOfDays':
                    setSingeTextFieldBlock();

                    textFieldFrom.addEventListener("change", event => {
                        fromInputValue = event.target.value

                        for (let i = 0; i < fromInputValue; i++) {
                            let previousDate = new Date(currentDate);
                            previousDate.setDate(currentDate.getDate() + i);
                            range.push(previousDate);
                        }
                        range.reverse();
                    })
                    break

                case 'exactDate':
                    setSingleDateFieldBlock()

                    fromInput.addEventListener("change", event => {
                        fromInputValue = event.target.value
                    })
                    break

                case 'range':
                setAllTextFieldsBlock()

                fromInput.addEventListener("change", event => {
                    fromInputValue = event.target.value
                })
                toInput.addEventListener("change", event => {
                    toInputValue = event.target.value
                })
                let currentDate = new Date(fromInputValue);
                while (currentDate <= toInputValue) {
                    range.push(new Date(currentDate));
                    currentDate.setDate(currentDate.getDate() + 1);
                } 
                break

            default:
              console.log('else')
        }
});
</script>

//html

<body>
  <div >
    <select class="form-select" id="example-select" name="example-select">
        <option selected="">Any date</option>
        <option value="yesterday">yesterday</option>
        <option value="today">today</option>
        <option value="tomorrow">tomorrow</option>
        <option value="recentWeek">recentWeek</option>
        <option value="recentMonth">recentMonth</option>
        <option value="recentQuarter">recentQuarter</option>
        <option value="last7Days">last7Days</option>
        <option value="last30Days">last30Days</option>
        <option value="last60Days">last60Days</option>
        <option value="last90Days">last90Days</option>
        <option value="lastNumberOfDays">lastNumberOfDays</option>
        <option value="nextNumberOfDays">nextNumberOfDays</option>
        <option value="exactDate">exactDate</option>
        <option value="range">range</option>
        <option value="previousWeek">previousWeek</option>
        <option value="previousMonth">previousMonth</option>
    </select>
    <input type="date" class="from-input" placeholder="Choose date"
        value="from">
  <input 
    style="display: none;"
    type="text" 
    class="text-field-from form-control" 
    placeholder="Enter number">
  <input type="date" class="to-input form-control "  placeholder="Till"
        value="to" />
  <input 
    style="display: none;"
    type="text" 
    class="text-field-to form-control" 
    placeholder="Choose date">
  </div>

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

u

Update child component in React with data from other child component

I am pretty new to React and am trying to solve something right now but somehow can’t get my head around the rendering process of React.
I have three components: 1 parent component, 2 child components.

Parent component is called “GaStructuresApp”.
Child 1 component is called “DropdownTreeSelect”.
Child 2 component is called “Keywords”.

GaStructuresApp receives data from an external system via an useEffect() hook and sets the received data via useState on the “DropdownTreeSelect” component.
I can now navigate via the structure in that child component and select different values (via checkbox). Every value in that checkbox has child-elements. These child-elements however should appear next to the “DropdownTreeSelect” component in an own div.
For this, I have the “Keywords” component which receives the child-elements of the selected item via props. Thus, I am also setting the value via a useEffect() for that component.
This works fine as well. However, now the “DropdownTreeSelect” component is collapsed again and nothing is checked. This is probably due to the fact that everything got re-rendered again.
I do not want the “DropdownTreeSelect” to re-render when I click the checkbox. I only want the “Keywords” component to re-render, since that component received the new props.

Here is some code (obfuscated to the important points):

“GaStructuresApp”:

export default function GaStructuresApp() {

    const [keywordsAll, setKeywords] = useState([]);

...

    function onChange(currentNode, selectedNodes) {

        keywordsAll.splice(0, keywordsAll.length);
        setKeywords([...keywordsAll]);


        selectedNodes.forEach(node => {
            if (node.checked === true) {
                if (node.kids.length > 0) {
                    getChildrenValues(node);
                }
                else {
                    node.keywords?.forEach(keyword => {
                        keywordsAll.push(keyword);

                        setKeywords([...keywordsAll]);
                    })
                }
            }
        })

        buildPaths(selectedNodes);
    }

...

return(<> <div className={"dropdown"}><DropdownTreeSelect data={data} onChange={onChange} showDropdown={"always"}/> </div> <Keywords keywords={keywordsAll}/> </>)

“Keywords”:

import React from 'react';

export default function Keywords ({keywords}) {

    return (
        <div className={"keywordsBox"}>
            <ul>
                {keywords.map((keyword) => (
                    <li id={keyword.id}>
                        {keyword.value}
                    </li>
                ))}
            </ul>
        </div>


    );
}

How can i add a button to my website to download images from other websites?

I tried this code, but it’s not working, when I click the button it opens the image in the browser!

<head>

  <title>Image Downloader</title>

</head>

<body>

  <button id="downloadBtn">Download Image</button>

    var imageUrl = 'https://example.com/image.jpg'; // Replace with the URL of the image you want to download

    var link = document.createElement('a');

    link.href = imageUrl;

    link.download = 'image.jpg';

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);

});

</script>

</body>

</html>

How to Override Chrome Extension Styles

How to override the styles of Chrome extensions like Midnight Lizard or Dark Reader?

I’m working on a USERJS, and some styles are getting overridden by these dark mode extensions. Their styles always seem to have the highest priority. I’ve tried deleting style tags and removing document.styleSheets, but it doesn’t seem to work. How can I either delete or override their styles within the USERJS environment?

English is not my native language, and this article has been translated by CHATGPT, so please bear with me.

How to sort an array of coordinate objects clockwise or counterclockwise?

I have an array of coordinate objects, and I need to implement a sorting mechanism that arranges them either in a clockwise or counterclockwise direction.

This array:

    [
      { x: 0, y: 108 },
      { x: 0, y: 54 },
      { x: 108, y: 108 },
      { x: 54, y: 54 },
      { x: 108, y: 0 },
      { x: 54, y: 0 }
    ]

should be sorted into this:

    [
      { x: 54, y: 0 },
      { x: 108, y: 0 },
      { x: 108, y: 108 },
      { x: 0, y: 108 },
      { x: 0, y: 54 },
      { x: 54, y: 54 }      
    ]

The starting point can be any.

example

Tile size is 54.

Where can arbitrary code be placed in Nuxt 3?

I’m facing confusion due to the different purposes of numerous folders in Nuxt 3. I want to store a simple food list array in a JavaScript file and export it, but I’m uncertain about the appropriate location to place this file.

This is my food.js file:

export const food = ['apple', 'banana', 'some random fruit']

Typically, if I’m not using Nuxt 3, I would place the food.js file next to the component that will utilize it, like this:

  1. components/myFolder1/FoodView.vue
  2. components/myFolder1/food.js

However, in Nuxt 3, this approach is no longer feasible as my food.js file will be automatically registered as a component due to Nuxt 3’s mechanisms.

Placing food.js in the composables/ folder doesn’t make sense since it’s just a static file.

Although putting food.js in the utils/ folder seems reasonable, the utils/ folder doesn’t scan nested folders for auto-registration. For instance:

If my utils/ folder looks like this:

  1. utils/formatDate.js
  2. utils/foodApp/food.js

Nuxt 3 will only auto-import formatDate.js and ignore food.js. I would have to manually import food.js, which deviates from Nuxt 3 conventions and potentially complicates the project’s comprehension. Additionally, the utils/ folder isn’t an ideal place to store this type of arbitrary code.

Hence, I’m seeking advice on the best location to store such arbitrary code in Nuxt 3.

Getting 12:00 hour format time in html using JavaScript

I’m trying to figure how to convert several time zone hours into the 12:00 hour format rather than the 24:00 format using HTML with Script tag

<!DOCTYPE HTML>
<html lang = "en">
<head>
<meta charset="UTF-8">
<title>Time Web Page</title>

</head>


<body>
<noscript>JavaScript Not Enabled!</noscript>

<h1>Time Zones Around the World!</h1>
<hr>
<h2>San Francisco</h2>
<h3><p id="p1"></p></h3>

<script>
var date = new Date();
var current_time = date.getHours()-3+":"+date.getMinutes()+":"+ date.getSeconds();
document.getElementById("p1").innerHTML = current_time;
</script>

<br>

<h2>Chicago</h2>
<h3><p id="p2"></p></h3>

<script>
var date = new Date();
var current_time2 = date.getHours()-1+":"+date.getMinutes()+":"+ date.getSeconds();
document.getElementById("p2").innerHTML = current_time2;
</script>

Forgot to Mention how i need BOTH the 24 format AND the 12 format which i’m not sure if i should add more code for that or re-adjust my code

How to know if textarea is actively being resized

I’m looking for a javascript function that will return true if a given textarea element is being resized, and return false if it’s not. Does this function exist, without the use of JQuery or any other tool like that, and if it doesn’t, how could I make it?

Thanks in advance!