Does anyone know how I can keep my elements in the same position when zoomed in and out on a webpage?

Im pretty new to coding, and I was wondering if there is anything I can do in CSS, HTML, or JS that would stop my elements from moving around without using position: fixed; When I zoom out on a webpage or zoom in my elements such as images and paragraphs move everywhere and my nav bar doesn’t expand to the size.

I’ve tried a couple of things like using a container and editing the padding and margin and looked into some media queries but im pretty new to coding and self-learning so im not sure where to look or what I need to research this.

How to make the user follow the randomize array by clicking different jbuttons?

So I’m making a food game, where I have the ingredients in Jbuttons icon and the order to put ingredient in a randomize array. And here is the problem, what code can I use to let the user “can” only click the jbuttons in the randomize order, and once they click the wrong ingredient, there will be a try again JOptionPane?

I have no idea what code I can use to make it work, these are a part of my codes:

//array ingredients order
        String [] ingredients = {"Tomato", "Lettuce", "Egg", "Sauce", "Meat", "Onion", "Cheese", "Cucumber"};
        List<String> ingredientsList = Arrays.asList(ingredients);
        Collections.shuffle(ingredientsList);
        ingredients = ingredientsList.toArray(new String[0]);
    
        JLabel food = new JLabel(Arrays.toString(ingredients));
        food.setFont(new Font("Monospaced", Font.PLAIN, 14));
        food.setBounds(228, 58, 516, 48);
        contentPane.add(food);

and some of the jbuttons

JButton tomato = new JButton("");
        tomato.setOpaque(false);
        tomato.setContentAreaFilled(false);
        tomato.setBorderPainted(false);
        tomato.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                tomatoslide.setVisible(true);
                
            }
        });
        tomato.setIcon(new ImageIcon(game_food_1.class.getResource("/images/tomato.png")));
        tomato.setBounds(16, 364, 90, 90);
        contentPane.add(tomato);
        
        JButton sauce = new JButton("");
        sauce.setOpaque(false);
        sauce.setContentAreaFilled(false);
        sauce.setBorderPainted(false);
        sauce.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                sauceslide.setVisible(true);
            }
        });
        sauce.setIcon(new ImageIcon(game_food_1.class.getResource("/images/sause.png")));
        sauce.setBounds(137, 364, 90, 90);
        contentPane.add(sauce);

Javascript unable to display JSON value [duplicate]

I am submitting to a php file for processing the form and creating a json encoded response, but in the javascript code I am not able to retrieve the value for the key and is returning as undefined. If I print the result, I can see the array object returned as set in the php code. How can I return the key value in the javascript?


//json response set in php file

{"status":"some status","data":"some random data"}

//javascript - jquery code snippet
:
:
onSuccess: function (e) {
e.preventDefault();
var form_data = new FormData($('#form')[0]);
$.ajax({
    url: $('#form').attr('action'),
    type: 'POST',
    cache: false,
    processData: false,
    contentType: false,
    data: form_data,
    success: function (result) {
    alert(result.status);//returning as undefined 
        },
    error: function (xhr, status, error) {
        }
    });
}
:
:

I am expecting to get the value of status back when processing it from Javascript. I have set the json encoded response from the php and is received correctly in the result object as an array, but I am not able to print the value of the key status.

Puppeteer NodeJS How would I get an element value by class?

I want to get the values of “data id” using the class below and put them into an array.

<div data-id="111" class="tr svelte-1q11k9a" style="z-index: auto;">
<div data-id="222" class="tr svelte-1q11k9a" style="z-index: auto;">
<div data-id="333" class="tr svelte-1q11k9a" style="z-index: auto;">

I have tried this but it returned “undefined”.

const ex = await page.$$eval("div[class='tr svelte-1q11k9a']", ({ data-id }) => data-id);
    console.log(ex)

How to maintain k largest numbers in priority-queue in javascript?

leetcode is using this heap queue api: https://www.npmjs.com/package/@datastructures-js/priority-queue (maxQueue and minQueue)

I remember that is a question (cannot recall the question number)

for example, random integer input:

[1, 2, 3, 4, 5, 6, ….]

for example, queue (max size is 3; largest of 3 integer, in real time)

[10, 9, 8]

note:
we don’t want to push all elements into the priority queue (or heat), then dequeue largest Kth num (e.g. image the input is unlimited steam)

in summary is:

  1. use apis here: https://www.npmjs.com/package/@datastructures-js/priority-queue
  2. input are integer with duplicated number.
  3. real time priority queue max size is 3 (i.e. size > 4 is invalid)
  4. I wonder how to achieve this, due to the fact that I can push to the end, and pop at the front only.

Is there a way to display data from Google’s response?

So currently I have code to mimic Google’s webpage (although a very very bad/basic version), and also a backend server that I run on my computer. When a client uses the webpage and types something in, the backend server will get that request and request it to Google, and then it will get a response from Google. I need help displaying the response from Google, as well as adding support to visit actual websites within the webpage (e.g. youtube or other websites). Here’s my code:

Index.js-

let tabCount = 1;

function showTab(tabId) {
  const tabs = document.querySelectorAll('.tab-content');
  tabs.forEach(tab => {
    tab.classList.remove('active');
  });
  document.getElementById(tabId).classList.add('active');

  const tabElements = document.querySelectorAll('.tab');
  tabElements.forEach(tab => {
    tab.classList.remove('active');
  });
  event.target.classList.add('active');
}

function addNewTab() {
  tabCount++;
  const newTabId = `tab${tabCount}`;
  const newTab = document.createElement('div');
  newTab.className = 'tab';
  newTab.textContent = `Tab ${tabCount}`;
  newTab.setAttribute('onclick', `showTab('${newTabId}')`);
  document.querySelector('.add-tab').before(newTab);

  const newTabContent = document.createElement('div');
  newTabContent.id = newTabId;
  newTabContent.className = 'tab-content';
  newTabContent.innerHTML = `
    <img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="Google Logo" class="logo">
    <div class="search-box">
      <input type="text" id="${newTabId}-search-input" placeholder="Search Google or type a URL">
      <button id="${newTabId}-search-btn">&#x1F50D;</button>
    </div>
    <div class="buttons">
      <button>Google Search</button>
      <button>I'm Feeling Lucky</button>
    </div>
    <div id="${newTabId}-results" class="search-results">
      <iframe id="${newTabId}-iframe" class="search-iframe" style="width: 100%; height: 80vh; display: none;" frameborder="0"></iframe>
    </div>
  `;
  document.body.appendChild(newTabContent);
}

document.addEventListener("keydown", function (event) {
  if (event.key === "Enter") {
    const activeTab = document.querySelector('.tab-content.active');
    const searchInput = activeTab.querySelector('input[type="text"]');
    const inputValue = searchInput.value;

    const isUrl = /^https?:///i.test(inputValue);
    const fetchUrl = isUrl ? `/urls?url=${encodeURIComponent(inputValue)}` : `/search?q=${encodeURIComponent(inputValue)}`;

    fetch(fetchUrl)
      .then((response) => response.text())
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.error(error.message);
      });
  }
});

Server.js-

const express = require('express');
const https = require('https');
const http = require('http');
const app = express();
const port = 5505;

app.use(express.static('public'));

const rewriteUrls = (html, baseUrl) => {
    return html.replace(/(href|src)="([^"]*)"/g, (match, attr, url) => {
        const absoluteUrl = new URL(url, baseUrl).toString();
        return `${attr}="/proxy?url=${encodeURIComponent(absoluteUrl)}"`;
    });
};

app.get('/search', (req, res) => {
    const query = req.query.q;
    const googleSearchUrl = `https://www.google.com/search?q=${encodeURIComponent(query)}`;
    https.get(googleSearchUrl, (response) => {
        let data = '';
        response.on('data', chunk => {
            data += chunk;
        });
        response.on('end', () => {
            const rewrittenData = rewriteUrls(data, googleSearchUrl);
            res.send(rewrittenData);
        });
    }).on('error', (err) => {
        res.status(500).send('Error: ' + err.message);
    });
});


app.get('/urls', (req, res) => {
  let targetUrl = req.query.url;
  const client = targetUrl.startsWith('https://') ? https : http;

  client.get(targetUrl, (response) => {
    let data = '';
    response.on('data', (chunk) => {
        console.log('Sending URL results back');
      data += chunk;
    });
    response.on('end', () => {
      res.send(data);
    });
  }).on('error', (err) => {
    console.error('Error fetching URL:', err);
    res.status(500).send('Error: ' + err.message);
  });
});

app.get('/proxy', (req, res) => {
    const resourceUrl = req.query.url;
    https.get(resourceUrl, (response) => {
        response.pipe(res);
    }).on('error', (err) => {
        res.status(500).send('Error: ' + err.message);
    });
});


app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Index.html-

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Thing</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f1f3f4;
    }
    .tabs {
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: white;
      border-bottom: 1px solid #ccc;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
      padding: 10px 0;
      position: sticky;
      top: 0;
      z-index: 10;
    }
    .tab {
      padding: 10px 20px;
      margin: 0 5px;
      cursor: pointer;
      font-size: 16px;
      color: #5f6368;
      border-bottom: 3px solid transparent;
      transition: border-color 0.3s;
    }
    .tab:hover {
      color: #202124;
    }
    .tab.active {
      color: #1a73e8;
      border-bottom: 3px solid #1a73e8;
    }
    .add-tab {
      font-size: 24px;
      font-weight: bold;
      cursor: pointer;
      color: #5f6368;
      padding: 0 10px;
      transition: color 0.3s;
    }
    .add-tab:hover {
      color: #202124;
    }
    .tab-content {
      display: none;
    }
    .tab-content.active {
      display: block;
      text-align: center;
      margin-top: 50px;
    }
    .logo {
      margin: 20px auto;
    }
    .search-box {
      margin: 20px auto;
      width: 60%;
      display: flex;
      align-items: center;
      border: 1px solid #dfe1e5;
      border-radius: 24px;
      background-color: white;
      padding: 5px 15px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
    .search-box input {
      flex: 1;
      border: none;
      outline: none;
      font-size: 16px;
      padding: 10px;
    }
    .search-box button {
      background: none;
      border: none;
      cursor: pointer;
      color: #5f6368;
      font-size: 18px;
    }
    .buttons {
      margin: 20px auto;
    }
    .buttons button {
      margin: 5px;
      padding: 10px 20px;
      font-size: 14px;
      color: white;
      background-color: #1a73e8;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    .buttons button:hover {
      background-color: #1669c1;
    }
  </style>
</head>
<body>
  <div class="tabs">
    <div class="tab active" onclick="showTab('tab1')">Tab 1</div>
    <div class="add-tab" onclick="addNewTab()">+</div>
  </div>
  <div id="tab1" class="tab-content active">
    <img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="Google Logo" class="logo">
    <div class="search-box">
      <input type="text" placeholder="Search Google or type a URL">
      <button>&#x1F50D;</button>
    </div>
    <div class="buttons">
      <button>Google Search</button>
      <button>Random Button</button>
    </div>
  </div>
  <script src="index.js"></script>
</body>
</html>

Error , list reloads after, open or close v-navigation-drawer on vuetify, causes slowness

Sumary

Using vuetify, v-navigation-drawer or v-main,
I identified a severe slowdown in my application when there were many images on the page, and trying to scroll, or open the navigation-drawer, it would hang.

So I inserted logs into the loop and found that the list was reloading when open the panel.

It seems unnoticeable on the list.
but, it caused crashes and slowness, when load many images.

I create, in vuetify play , more simple version to demonstrate.

Example LINK

Click here to open a Example In Vuetify Play

Details:

The example should contain a data list a v-for, which will display a lot of data, preferably images, basically a v-for, and a v-navigation-drawer panel

1 Click on button 1 ADD RECORDS TO THE LIST +30 onClick to add, more records, to test.

2 open your console to view logs .

I inserted a command to insert logs inside v-for.

This way I discovered the reason for the slowness.

3 CLEAR THE CONSOLE

use the button, if you see log records in the console, to observe when you will add new logs, when opening the panel

4 – Toggle v-navigation-drawer visible, and observe logs

5 – Conclusion Description Error, cause slowless

Apparently the list is re-rendered after opening the v-navigation-drawer panel. Clean the console. observe the console. when opening v-navigation-drawer, it will add the log records again. with each click + 30 records will be added. It depends on the machine to observe the slowness. In mine, I see slowness with 1000 records. When panel open, the log was added , the list refresh, it is not perceptible, but causes slowess, when opening the panel, and the scrolling lists. Its not perceptible, with simple records, but, cause, very sloly, For me, Its cause very slowly when using more lot records, or 200 images. if you add more records you can see the slowdown happening.

6 This code example:

<template>
  <v-app>
    <v-main>
      <v-card>
        <v-container>
          <v-row>
            <v-col><h1>Error on v-navigation-drawer test.</h1></v-col>
          </v-row>
          <v-row>
            <v-col><h2>Description:</h2></v-col>
          </v-row>
          <v-row>
            <v-col
              ><p>
                Apparently the list is re-rendered after opening the
                v-navigation-drawer panel
              </p></v-col
            >
          </v-row>
          <v-row>
            <v-col>
              <v-btn color="primary" @click="loadList()" variant="outlined">
                1 ADD RECORDS TO THE LIST +30 onClick
              </v-btn>
            </v-col>
            <v-col>
              <p>
                Total de Registros:
                <strong> {{list_products.length}} </strong>
              </p></v-col
            >
          </v-row>
          <v-row></v-row>
          <v-row>
            <v-col
              ><h3>2 open your console to view logs .</h3>
              <p>
                I inserted a command to insert logs inside v-for. This way I
                discovered the reason for the slowness.
              </p></v-col
            >
          </v-row>
          <v-row>
            <v-col></v-col>
          </v-row>
          <v-row>
            <v-col
              ><v-btn
                color="primary"
                @click="clearConsole()"
                variant="outlined"
              >
                3 CLEAR THE CONSOLE
              </v-btn>
            </v-col>
            <v-col
              ><v-switch
                v-model="autoClear"
                label="Auto Clear After Load"
              ></v-switch
            ></v-col>
          </v-row>
          <v-row>
            <v-col
              ><p>
                use the button, if you see log records in the console, to
                observe when you will add new logs, when opening the panel
              </p></v-col
            >
          </v-row>
          <v-row>
            <v-col>
              <v-btn
                color="primary"
                @click.stop="drawer = !drawer"
                variant="outlined"
              >
                4 - Toggle v-navigation-drawer visible, and observe logs
              </v-btn></v-col
            >
            <v-col
              ><v-switch v-model="drawer" label="PANEL IS VISIBLE"></v-switch
            ></v-col>
          </v-row>
          <v-row>
            <v-col><h2>Conclusion Description Error:</h2></v-col>
          </v-row>
          <v-row>
            <v-col
              ><p>
                Apparently the list is re-rendered after opening the
                v-navigation-drawer panel
              </p></v-col
            >
          </v-row>
          <v-row>
            <v-col>
              <p>
                Clean the console. observe the console. when opening
                v-navigation-drawer, it will add the log records again.
              </p>
              <p>
                with each click + 30 records will be added. It depends on the
                machine to observe the slowness. In mine, I see slowness with
                1000 records.
              </p>
              <p>
                the log was added , the list refresh, it is not perceptible, but
                causes slowess, when opening the panel, and the scrolling lists.
                <br />
                For me, Its cause very slowly when using 300 images.
                <br />
                Its not perceptible, with simple records, but, cause, very
                sloly, when loading, 300 images,
              </p>
            </v-col>
          </v-row>
          <v-row
            ><v-col><h2>Table Data</h2></v-col></v-row
          >
          <v-row>
            <v-col>
              <table class=".table-bordered">
                <tbody v-for="prod in list_products" :key="prod.id">
                  <tr>
                    <td>
                      {{prod.title}}
                      {{logDebug("itemreconsultadonalista",prod)}}
                    </td>
                    <td>{{prod.rating}}</td>
                    <td>{{prod.shippingInformation}}</td>
                    <td>{{prod.reviewerName}}</td>
                    <td>{{prod.reviewerEmail}}</td>
                    <td>{{prod.availabilityStatus}}</td>
                    <td>{{prod.availabilityStatus}}</td>
                    <td>{{prod.price}}</td>
                    <td>{{prod.tags}}</td>
                  </tr>
                  <tr>
                    <td colspan="9">{{prod.description}}</td>
                  </tr>
                  <tr>
                    <td colspan="9">
                      <table>
                        <tbody v-for="img in prod.images">
                          <tr>
                            <td><img :src="img" />{{img}}</td>
                          </tr>
                        </tbody>
                      </table>
                    </td>
                  </tr>
                </tbody>
              </table>
            </v-col>
          </v-row>
        </v-container>
      </v-card>
    </v-main>
    <v-navigation-drawer v-model="drawer" temporary location="right">
      <v-card>
        <v-container>
          <v-btn
            color="primary"
            @click="clearConsole()"
            variant="outlined"
            block
          >
            2 CLEAR THE CONSOLE
          </v-btn>
          <v-btn
            block
            color="primary"
            @click.stop="drawer = !drawer"
            variant="outlined"
          >
            CLOSE
          </v-btn>
        </v-container>
      </v-card>
    </v-navigation-drawer>
  </v-app>
</template>

<script>
  export default {
    data: () => ({
      autoClear: true,
      title: 'Error on v-navigation-drawer test.',
      teste_nav: { open: false },
      list_images: [],
      list_products: [],
      drawer: false,
      warns: {
        list: true,
      },

      fake: undefined,
      newName: undefined,
      newNumber: undefined,
      people: [{ name: 'Alpha', number: 1 }],
      headers: [
        { text: 'Name', value: 'name' },
        { text: 'Number', value: 'number' },
        { text: 'Inputs', value: 'name' },
      ],
    }),

    methods: {
      logDebug(pstr, item) {
        console.warn(pstr, item.title)
      },
      clearConsole() {
        console.clear()
      },
      loadList(pstr) {
        console.log('loadList')
        const self = this

        this.warns.list = false

        /* providing access token in bearer */
        fetch('https://dummyjson.com/products', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
        })
          .then(r => r.json())
          .then(json => {
            console.log('json', json)

            for (var i = 0; i < json.products.length; i++) {
              var item = json.products[i]
              self.list_products.push(item)
            }
            window.setTimeout(function () {
              console.clear()
            }, 100)
          })
      },
    },
    
  }
</script>

7 Can anyone tell me what I did wrong??

Thanks!

HTML not recognizing declared variable in seperate .js file

I am trying to write a simple webpage that takes in a binomial and prompts gpt-4o-mini to create similar ones. This is pretty much my first venture into this kind of thing so forgive me if the solution is obvious. The issue is that when the button is pressed, it says that the function is not defined, and stops the program.

The page:

<!DOCTYPE html>

<html>

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


    </head>
    <body>
            <input type="text" id="input">
            <button id="button" type="button" onclick="double()">Write</button>
            <h4 id="output"></h4>
    </body>

main.js:

import OpenAi from "./node_modules/openai";
const openai = new OpenAi();


async function double() {
    var input = document.getElementById("input").value();

    const completion = await openai.chat.completions.create({
     model: "gpt-4o-mini",
     messages: [
        {role:"user",
            content:"Write a solvable binomial similar to this one: " + input
        },
     ],
});

document.getElementById("output").innerHTML = completion.choices[0].message;
}

I’ve tried multiple fixes such as changing the function name, checking for spelling errors, changing attributes in the script tag, to no avail. I’m just lost for what to do at this point.

If it matters, here is the path in the page’s folder:
enter image description here

Getting error “non-top-level require() call” with no require() beign used

I’m trying to move a web made with vanilla JS to node.js and I’m getting this error using Parcel2:

@parcel/transformer-js: Conditional or non-top-level `require()` call. This causes the resolved module and all dependencies to be wrapped.

  C:Usersxxxzabbix_console.js:1:1
  > 1 | import { sendNotification, fetchResource, clipboardCopy, ENDPOINT, getSetting, saveSetting } from "../libs/utils.js";
  >   | ^
    2 | import { getUserData } from "../libs/login.js";
    3 | import  {EVENT_TYPE } from "../libs/events.js";

  ℹ Learn more: https://parceljs.org/features/scope-hoisting/#avoid-conditional-require()

@parcel/core: Asset graph walked
@parcel/core: Asset graph walked
- Building runtime-9b535c67382b3742.js...

But the problematic file is not using require() anywhere, also it’s dependencies. The file utils.js has this at the top:

import { EVENT_TYPE } from "./events.js";

export const ENDPOINT = "http://localhost:8080";

...

events.js doesn’t use any import whatsoever, so I don’t know where the error is…

Things I’ve tried, from searching on the web:

  • Renaming the extension to .mjs
  • Setting the target in package.json and telling it is a esmodule.
  • Using type: module in package.json.
  • Deleting .parcel-cache and rebuiding.
  • Using .parcelrc to tell what transformers to use for .js/.mjs files.

I don’t have much experience with this, so I’m kinda stuck.

EDIT 11/25

Seems like adding --no-optimize to the build command, compiles the code… I’m still getting the require() error, but everything compiles. I still don’t know why.

Update object on click

I’m trying to add a youtube playlist to my website using a tutorial/code. I’m not sure what to do if the there are more than 50 results. I checked the youtube/google api documentation and got a nextPageToken but I’m not sure what to do with it. How do I add pageToken/nextPageToken/prevPageToken objects (?) to the options variable so that it will update the playlist when I click a button? I want to add pagination to the results without reloading the page.

Here is the code from the tutorial. It works as is but I can’t view more than 50 videos (the playlist I’m using has about 120). When I add pageToken: nextPageToken to the options, it says that nextPageToken is not defined. How do I define it and the previousPageToken and use them to update the pageToken object and change the results on the page?

$(document).ready(function () {

    var key = [YOUR API KEY HERE];
    var playlistId = 'PL2fnLUTsNyq7A335zB_RpOzu7hEUcSJbB';
    var URL = 'https://www.googleapis.com/youtube/v3/playlistItems';


    var options = {
        part: 'snippet',
        key: key,
        maxResults: 50,
        playlistId: playlistId
    }

    loadVids();

    function loadVids() {
        $.getJSON(URL, options, function (data) {
            var id = data.items[0].snippet.resourceId.videoId;
            mainVid(id);
            resultsLoop(data);
        });
    }

    function mainVid(id) {
        $('#video').html(`
                    <iframe width="560" height="315" src="https://www.youtube.com/embed/${id}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
                `);
    }

        
    function resultsLoop(data) {

        $.each(data.items, function (i, item) {

            var thumb = item.snippet.thumbnails.medium.url;
            var title = item.snippet.title;
            var desc = item.snippet.description.substring(0, 100);
            var vid = item.snippet.resourceId.videoId;


            $('main').append(`
                            <article class="item" data-key="${vid}">

                                <img src="${thumb}" alt="" class="thumb">
                                <div class="details">
                                    <h4>${title}</h4>
                                    <p>${desc}</p>
                                </div>

                            </article>
                        `);
        });
    }

        // CLICK EVENT
    $('main').on('click', 'article', function () {
        var id = $(this).attr('data-key');
        mainVid(id);
    });


});

Js Script Async function removing a class before its intended

— [Context] ————————————————-

I’ve been doing a custom dropdown box that is composed of an input, i know there is a input type select, however i would like that my list of elements could be opened by an external button or by the input field that contains

The dropdown box works as intented, I did it with help of this tutorial “https://www.youtube.com/watch?v=cNdJLapVQMo” however I modified the js script so that it can all for multiple custom dropdown boxes exist in the same page. Also I’m yet to add a function that shows the content selected in the dropdown box inside the input but that is not the problem I want to fix a bug first.

— [Problem] ————————————————-

I have two custom dropdown boxes one is on top of the other, when i click on the input field it opens the dropdown box of the selected element and inside it add the class ‘chosen’ (class that changes the z-index so that the dropdown element is on top of everything) to the dropdown element (represents the input, and the list of elements), when i click on the same input field again, what i want it to do is

  1. Enter the closeDropdown function (self-explanatory)

  2. Remove the ‘chosen’ class from my dropdown element
    (this is so that the elemnt is no longer of top of the other dropdown boxes once I open antoher dropdown box)

This is how it normally looks like

enter image description here

However this happens…
The bug i’m facing

Here is my js script

<script>
    document.addEventListener("DOMContentLoaded",loadDropdowns);

    let dropdowns = "";


    function loadDropdowns(){
      dropdowns = document.querySelectorAll(".dropdown");
      console.log(dropdowns);
    }


      let dropdownChosen = document.querySelector(".dropdown.chosen");
      setTimeout(() => {
      // I aded this so that the chosen class wasn't removed bed
          console.log('espera');
        }, 250);
      console.log(dropdownChosen);

      if(dropdownChosen != null ){
        let wasClicked = dropdownChosen.querySelector(".input-box").contains(event.target);
        if(!wasClicked){
          console.log("hewwo");
          closeDropdown(dropdownChosen.querySelector(".input-box"),dropdownChosen.querySelector(".list"));
        }
      }


      dropdowns.forEach((dropdown)=>{

        let clickedInside = false;

        const inputBox= dropdown.querySelector(".input-box");
        const list = dropdown.querySelector(".list");

        if(inputBox.contains(event.target) || list.contains(event.target)){
          clickedInside = true;
          dropdown.classList.add("chosen");

          if(inputBox.contains(event.target)){
            toggleDropdown(inputBox, list);
          }
        }
        else {
          closeDropdown(inputBox,list);
        }

        if(!clickedInside || inputBox.maxHeight===null){
          dropdown.classList.remove("chosen");
        }

      });

    });


    async function toggleDropdown(inputBox,list){
      const isOpen = inputBox.classList.toggle("open");
      if(isOpen){
        list.style.maxHeight = list.scrollHeight + "px";
        list.style.boxShadow =  "0 1px 2px 0 rgba(0, 0, 0, 0.151), 0 1px 3px 1px rgba(0, 0, 0, 0.1)";
      }
      else{
        closeDropdown(inputBox, list);
      }
    }

    async function closeDropdown(inputBox, list){
      inputBox.classList.remove("open");
      // quita la clase open

      list.style.maxHeight = null;
      list.style.boxShadow = null;
    }

  </script>

Here is my html code

<body>
  <div class="center">
    <div class="dropdown">
      <div class="input-box"></div>
      <div class="list">
        <input type="radio" name="option1" id="opt1">
        <label for="opt1">Option 1</label>
        <input type="radio" name="option1" id="opt2">
        <label for="opt2">Option 2</label>
      </div>
    </div>

    <div class="dropdown">
      <div class="input-box">Dropdown 2</div>
      <div class="list">
        <input type="radio" name="option2" id="opt3">
        <label for="opt3">Option A</label>
        <input type="radio" name="option2" id="opt4">
        <label for="opt4">Option B</label>
      </div>
    </div>
  </div>

and here is my stylesheet

<style>
    body{
      margin:0;
      padding: 0;
      width:100%;
      height: 100vh;
      background-color: white;
    }

    .center{
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .dropdown{
      width:300px;
      height: fit-content;
      box-sizing: border-box;
      position: relative;
    }

    .input-box{
      width: 100%;
      height: 40px;
      box-sizing: border-box;
      outline: 0.3mm solid rgba(0, 0, 0, 0.164);
      border-radius: 2mm;
      padding: 10px 15px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      /* aqui puedes cambiar la fuente */
      z-index: 1;
    }

    .input-box:hover{
      outline: 0.3mm solid dodgerblue;
    }

    .chosen {
      z-index: 2;
    }

    /* puedes poner texto dentro del input si es que no hay */
    .input-box:empty::after{
      content:"Elige una persona...";
      color: rgba(0,0,0,0.5);
    }

    /* controla los elementos de la lista desplegable */
    .list{
      position: absolute;
      top: 100%;
      left: 0;
      width: 100%;
      background: white;
      margin-top: 10px;
      border-radius: 2mm;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-direction: column;
      max-height: 0;
      transition: 0.25s ease-in-out;
    }

    /* hace que el label abarque todo el espacio de la lista */
    .list label{
      display: flex;
      width: 100%;
      align-items: center;
      justify-content: start;
      padding: 10px 15px;
      box-sizing: border-box;
      cursor: pointer;
      position: relative;
      /* aqui puedes cambiar la fuente */
    }

    /* oculta el boton input donde se puede seleccionar las opcciones */
    .list input{
      display: none;
    }

    .list label:hover{
      background: rgba(202, 202, 202, 0.08);
    }

    input:checked + label{
      color: rgb(58, 147, 236);
      background: rgb(215, 235, 255) ;
    }

    input:checked + label::before {
      content: "done"; /*Aqui poner icono como flecha que signfica seleccionado o algo asi*/
      position: absolute;
      top: 50%;
      right: 15px;
      transform: translate(0,-50%);
      font-size: 10px;
    }

    /* hace que no cambie el hover cuando la propiedad ya fue seleccionada :) */
    input:checked + label:hover{
      color: rgb(58, 147, 236);
      background: rgb(215, 235, 255);
    }

    .open{
      outline: 0.7mm solid dodgerblue;
    }

    .title{
      font-family: poppins;
      font-size: small;
      font: 500;
      margin-bottom: 10px;
      color: red;
    }

  </style>

Im using all this code on the same html file, i tried adding the setTimeout,so that i woudl first show me what’s inside of dropdownChosen but it jumps straight to the ‘hewwo’ console.log, there is a furry ghost in my machine pls help

It sends first the hewwo message and then the dropdown console log

React Native and webpack

it has been a while since I did some web coding. I tried to build a simple app using React Native. Once I started I wondered how I could view the app in the browser. Some LLMing brought me to a combination of webpack and react-native-web.

So I essentially have a base folder where I have my ios, android and web folder. In the web folder I have a index.html and a index.js file.

Here is their content:

index.html

<!-- web/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React Native Web</title>
    <style>
      /* These styles make the body full-height */
      html,
      body {
        height: 100%;
      }
      /* These styles disable body scrolling if you are using <ScrollView> */
      body {
        overflow: hidden;
      }
      /* These styles make the root element full-height */
      #root {
        display: flex;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

index.js

// web/index.js
import { AppRegistry } from 'react-native';
import App from '../App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);
AppRegistry.runApplication(appName, {
  rootTag: document.getElementById("root")
});

My webpack.config.js looks like this:

const path = require('path');

module.exports = {
  entry: './web/index.js',
  output: {
    publicPath: path.resolve(__dirname, 'web'),
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /.(jpe?g|png|gif|svg)$/i, 
        loader: 'file-loader',
        options: {
          name: '/public/icons/[name].[ext]'
        }
      }
    ],
  },
  resolve: {
    alias: {
      'react-native$': 'react-native-web',
    },
    extensions: ['.web.js', '.js', '.jsx'],
  },
  devServer: {
    static: {
      directory: path.join(__dirname, 'web'),
    },
    compress: true,
    port: 9000,
  },
};

Here’s my App.js

// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/HomeScreen';
import CreatePostScreen from './screens/CreatePostScreen';
import LoginScreen from './screens/LoginScreen';

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Login">
        <Stack.Screen name="Login" component={LoginScreen} />
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="CreatePost" component={CreatePostScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

When I start webpack using webpack serve --mode development --open I get a blank HTML page. So it seems my actual App is never initialized. The only error I see in the console for webpack is:

WARNING in ./node_modules/react-native-screens/lib/module/components/ScreenStackItem.js 36:183-198
export 'FooterComponent' (imported as 'FooterComponent') was not found in './ScreenFooter' (possible exports: default)
 @ ./node_modules/react-native-screens/lib/module/index.js 19:0-74 19:0-74
 @ ./node_modules/@react-navigation/stack/lib/commonjs/views/Screens.js 14:12-43
 @ ./node_modules/@react-navigation/stack/lib/commonjs/views/Stack/CardStack.js 15:15-39
 @ ./node_modules/@react-navigation/stack/lib/commonjs/views/Stack/StackView.js 15:17-42
 @ ./node_modules/@react-navigation/stack/lib/commonjs/index.js 61:17-54
 @ ./App.js 1:274-308
 @ ./web/index.js 1:156-173

But that’s only a warning isn’t it?

make a value available otuside of this function to use in php later

im trying to turn the country_code var outside of the function to use later in a php. Here its working to display the value in a div. The issue im having is making the var available outside of the function, so I can turn it into a php var to use in php script later once a submit button is pressed

<html>
    <head>
      <script type="text/javascript">
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            var country_code = this.responseText.replace(/(rn|n|r)/gm,"").split('loc=');
            
            
            document.getElementById("countrycode-container").innerHTML = country_code;
          }
        };
        //OPEN HTTP Request
        xhttp.open("GET", "https://www.cloudflare.com/cdn-cgi/trace", true);
        xhttp.send();
      </script>
    </head>
    <body>
        <br><br><br>
    <div id="countrycode-container"></div>
    <br><br><br>
    </body>
    </html>

but I want to remove the div to use in a php script like this by just making a php var from the value of the javascript

             var xhttp = new XMLHttpRequest();
           
              //start of function
                xhttp.onreadystatechange = function() {
                   if (this.readyState == 4 && this.status == 200) {
                    let country_code = this.responseText.replace(/(rn|n|r)/gm,"").split('loc=');
                    country_code = country_code[1].split('tls=');
                    country_code = country_code[0];
                    document.getElementById("countrycode-container").innerHTML = country_code;
                    console.log(country_code);//will work here
                
                  }
            
                  
                };
                //end of function
                
                
                //OPEN HTTP Request
                xhttp.open("GET", "https://www.cloudflare.com/cdn-cgi/trace", true);
                xhttp.send();
        
 console.log(country_code);//need it to work here so i can take the value and turn it into php var
        
        // somehow convert from javascript var to php var
        //javascript var country_code
        //php var $country
        
        $country=country_code;
      
   
    
    
                if (isset($_POST['submit'])){
         code to check country code and do somin if match US,CA
        else{
         if empty or not US or CA do this
        }
        }

Vite build failed while working on an extension

I am working on a chrome plugin in Vue the build is failing again and again with the following error, I have a simple frontend for now no backend nothing fancy have never worked on a chrome extension before so wanted to test out with a basic UI.

x Build failed in 1.68s
x Build failed in 8.84s
error during build:
[web-extension:manifest] Invalid value "iife" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds.

The following is my vite config:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import webExtension from 'vite-plugin-web-extension';
import path from 'path';
import fs from 'fs-extra';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

function copyIcons() {
  return {
    name: 'copy-icons',
    buildEnd() {
      const iconDir = path.resolve(__dirname, 'src/icons');
      const distIconDir = path.resolve(__dirname, 'dist/icons');
      if (fs.existsSync(iconDir)) {
        fs.copySync(iconDir, distIconDir);
      }
    }
  };
}

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    webExtension({
      manifest: path.resolve(__dirname, 'src/manifest.json'),
      browser: 'chrome',
      webExtConfig: {
        browserConsole: false,
        startUrl: ['http://localhost:3000'],
      }
    }),
    copyIcons()
  ],
  build: {
    emptyOutDir: true,
    outDir: 'dist',
    modulePreload: false,
    cssCodeSplit: false,
    target: 'esnext',
    minify: 'terser',
    terserOptions: {
      format: {
        comments: false
      },
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    },
    rollupOptions: {
      input: {
        popup: path.resolve(__dirname, 'index.html'),
        background: path.resolve(__dirname, 'src/background.js'),
        contentScript: path.resolve(__dirname, 'src/contentScript.js')
      },
      output: {
        format: 'es',
        entryFileNames: '[name].js',
        chunkFileNames: 'chunks/[name].[hash].js',
        assetFileNames: 'assets/[name].[ext]',
        inlineDynamicImports: false
      }
    }
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  base: './',
  optimizeDeps: {
    exclude: ['webextension-polyfill']
  }
});

I have manifest.json in my src directory, a script directory with prepareextensions.js and normal vite project layout