How to make the Realtime Database data hauled in HTML, “searchable”

I have made a table data in HTML that has no content, basically just a th and a tr. Now, I haul the innerHTML of it and used my firebase data to change the value of the th and the tr. My only problem is it needs a second before it gets read, and now, whenever I use the search bar that I made, it does not read the new value of the th and the tr, rather, it only shows the premade values.

Is there a way to make this happen where the new data is searchable?

Here is how I changed the innerhtml:

firebase.initializeApp(firebaseConfig);
var firebaseRef = firebase.database().ref("message");
firebaseRef.on("value", function (snapshot) {
  var placementObjectrValuesSplit = Object.values(snapshot.val());
  valueMax = placementObjectrValuesSplit;
  // will show undefined if not defined or not yet present
  for (var x = 0; x <= placementObjectrValuesSplit.length - 1; x++) {
    // document.getElementById("date" + x).innerHTML = placementObjectrValuesSplit[x].pr[0];
    // document.getElementById("name" + x).innerHTML = placementObjectrValuesSplit[x].pr[1];
    // document.getElementById("sendoffice" + x).innerHTML = placementObjectrValuesSplit[x].pr[2];
    // document.getElementById("prNumber" + x).innerHTML = placementObjectrValuesSplit[x].pr[3];
    document.getElementById("recoffice" + x).innerHTML =
      placementObjectrValuesSplit[x].pr[4];
    // document.getElementById("reason" + x).innerHTML = placementObjectrValuesSplit[x].pr[5];
  }
});

For example, I have the original value of the first as “Treasury Office” and then, haul the innerhtml from the database.

enter image description here

However, whenever I search it:

enter image description here

What’s worse, if I erase the search, realtime database data does not refresh!

enter image description here

How do I get a javascript object from the Main process to the Renderer process in electron + webpack

I’m building an electron + webpack application. The result I’m trying to achieve is to load “config.yaml” as a javascript object in the main process (I think it has to, because renderer doesn’t have access to node’s “fs”) and then use IPC to move it over to renderer where I actually need it. The file structure looks like this:

- .webpack/
- node_modules/
- src/
+-- config.js
+-- header.js
+-- index.css
+-- index.html
+-- main.js
+-- preload.js
+-- renderer.js
+-- theme.js
- static/
+-- cfg/
  +-- config.yaml
+-- themes/
  +-- ...
- .gitignore
- forge.config.js
- package-lock.json
- package.json
- webpack.main.config.js
- webpack.renderer.config.js
- webpack.rules.js

main.js

const { app, BrowserWindow, Menu, ipcMain } = require('electron');
const fs = require('fs');
const yaml = require('yaml');
const theme = require('./theme.js');

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}

let config = fs.readFileSync('./static/cfg/config.yaml', 'utf8');
config = yaml.parse(config);

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: config.cl_win_width,
    height: config.cl_win_height,
    webPreferences: {
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
    },
  });

  // Remove the menu bar
  Menu.setApplicationMenu(null);

  // and load the index.html of the app.
  mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {

  // Config
  ipcMain.handle('config', () => {
    return config;
  })

  // Theme API
  ipcMain.handle('get-themes', () => {
    const fileList = fs.readdirSync('./static/themes');
    let themeList = theme.getThemes(fileList);
    return themeList;
  })

  createWindow();

  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

preload.js

// See the Electron documentation for details on how to use preload scripts:
// https://www.electronjs.org/docs/latest/tutorial/process-model#preload-scripts
const { ipcRenderer, contextBridge } = require('electron');
const header = require('./header.js');

contextBridge.exposeInMainWorld('mainAPI', {
    getConfig: () => ipcRenderer.invoke('config'),
});

contextBridge.exposeInMainWorld('themeAPI', {
    listThemes: () => ipcRenderer.invoke('get-themes'),
});

contextBridge.exposeInMainWorld('headerAPI', header);

renderer.js

import './index.css';

let headerAPI = window.headerAPI;

// Load config
let config;
window.mainAPI.getConfig().then(res => {
    console.log(res);
    config = res;
});

// Test this
console.log(config);

const content = document.querySelector('#content');

// Create Header
headerAPI.createHeader(content);

config.js

export async function getConfig() {
    // Makes call to main process and returns the config object
    let config = await window.mainAPI.getConfig();
    console.log(config);
    return config
}

Webpack is configured to use file-loader for my static files.

When I run this application with npm run, electron-forge . is executed, webpack compiles my code, and starts a dev server. The application window loads.

I expected to see the dev tools console display a message containing the javascript object logged out. This is what I see instead:

undefined                        renderer.js:19

{my javascript object}           renderer.js:14

In main, console logging the “config” object shows that it does load correctly.

In renderer, it logs correctly on line 14. My understanding is that because we wait for the async function to return before we log, line 14 should execute before line 19. An option I’ve considered is that “.then()” doesn’t stop the script from executing, which is why this error is occurring.

My question is this:

How do I get the config object from main over to renderer, and wait for it to be loaded before I proceed executing the rest of that script (mind, there’s going to be over 6000 lines of code, so I’ve nixed the disgusting idea of putting everything in the .then() scope).

Just a thought: I had done this before on this project’s previous iteration. I managed it simply by not using main to load the config, and instead had config.js use const fs = require('fs');, and defined a function loading it there, and then used preload to expose that. That no longer works here, because nothing except main.js can access fs now. I really have no idea how to proceed.

If anyone can help me understand what I’m missing here, and how to fix this issue, I would be most grateful. Thanks!

restructuring json data in reactjs

This is the json data I am pulling from the backend API:

[
    {
        "year": 2024,
        "month": 7,
        "revenue": 27000
    },
    {
        "year": 2024,
        "month": 8,
        "revenue": 27000
    }
]

However in order to use nivo line charts to graph the data the data must be in the following format.


Array<{
    id:   string | number
    data: Array<{
        x: number | string | Date
        y: number | string | Date
    }>
}>

I can manipulate the data on the backend but I’m having a hard time figuring out whether it’s easier to manipulate the data via the frontend to arrange in this format.

/ appeared in baseURL from nowhere

So i want to make a weather website, and i use axios. My problem is, that i made a baseURL and pasted an appid after it, so API works, and when i use it to get an info about the weather, i get “direct/?q=hamburg&……” but the problem here is that slash between direct and ?. I checked my code and cannot find where i wrote it, and because of that slash the whole thing doesnt work. Im sorry if its difficult to understand me, english is not my first language

I checked my whole code and didnt find a place where i put a slash in the link

Express and ytdl-core YouTube Video Info and Download API Not Working as Expected

I’m trying to create an API using Node.js with Express and ytdl-core to fetch YouTube video details and provide a download link. However, the API is not working as expected. Here is my code:

const express = require('express');
const ytdl = require('ytdl-core');
const cors = require('cors');
const app = express();
const port = 5000;

app.use(cors());

app.get('/video-info', async (req, res) => {
  const videoUrl = req.query.url;
  if (!ytdl.validateURL(videoUrl)) {
    return res.status(400).json({ error: 'Invalid YouTube URL' });
  }

  try {
    const info = await ytdl.getInfo(videoUrl);
    const formats = ytdl.filterFormats(info.formats, 'videoonly');
    const videoDetails = {
      title: info.videoDetails.title,
      duration: info.videoDetails.lengthSeconds,
      thumbnail: info.videoDetails.thumbnails[0].url,
      formats: formats.map(format => ({
        itag: format.itag,
        quality: format.qualityLabel,
        container: format.container,
      })),
    };
    res.json(videoDetails);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch video details' });
  }
});

app.get('/download', (req, res) => {
  const videoUrl = req.query.url;
  const itag = req.query.itag;

  if (!ytdl.validateURL(videoUrl)) {
    return res.status(400).json({ error: 'Invalid YouTube URL' });
  }

  res.header('Content-Disposition', 'attachment; filename="video.mp4"');

  ytdl(videoUrl, { filter: format => format.itag == itag }).pipe(res);
});

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

My problems are that the page is just loading and not downloading anything also somehow i made it work in the past but then there were errors with the encoder.

Max connections error with jawsdb with heroku when no users using app

I can use MySQL workbench and connect to by jawsdb database. Currently very little data in deployed app db. It’s a react app using node.js. I run SHOW processlist and it shows 9 processes in sleep. I manually KILL [process number] on a few of them. Then I restart dynos on heroku and then I can open and use the deployed app. I sign off and close the app. Then open it again and the same thing happens and I can resolve it the same way. I am using pooling. What are these connections to my database? Local environment working fine. Deployed version working fine as long as the new connections don’t start.

I added the pooling, I researched docs on heroku and jawsdb.

Javascript modal on element loaded dynamically after DOM load

Been trying to figure this out for a few days and I believe the issue has to do with event delegation, but I’m unsure how to solve it.

I have a website that loads a list of employees from the database. Each employee is placed in a card and when the card is clicked, a modal appears with additional information about the employee.

There are different departments, so in a top menu I dynamically load the department list from the database. I can then click on a department and use AJAX to only display the employees from the selected department. It looks exactly the same as the initial load, however the modal doesn’t work. When I look at the dev tool, I can see the data loaded for the department. Everything needed is loaded, except the modal will not open.
I can use the inspector to see the information is all loaded correctly, but I think the issue is that it was loaded to the page without a refresh.

I even tried to place the javascript in the get_organization_data.php in hopes it would work – but it didn’t.

Any thoughts?

//Open modal when clicking on employee card        
document.addEventListener("click", (e) => {
      if (e.target.matches(".employee_card")) {
        details.classList.remove("hidden");
        details.classList.add("overlay");
      }
    });
//Close modal when clicking on overlay
    document.addEventListener("click", (e) => {
      if (e.target.matches(".overlay")) {
        details.classList.remove("overlay");
        details.classList.add("hidden");
      }
    });
These are the AJAX calls

        $(document).on("click", ".org", function () {
          id = $(this).attr("id");
          // alert(id);
        
          $.ajax({
            url: "logic/get_organization_data.php",
            method: "POST",
            data: {
              id: id,
            },
            success: function (data) {
              $(".main_section").html(data);
              // $(".employee_modal").html(data); //thought this may be needed?
            },
         
          });
        });
    
    $(".main_section").on("click", "a", function (event) {
      event.preventDefault();
      id = $(this).attr("id");
      // alert(id);
      $.ajax({
        url: "logic/get_employee_data.php",
        method: "POST",
        data: {
          id: id,
        },
        success: function (data) {
          $(".employee_modal").html(data);
        },
        error: function () {
          alert("Error");
        },
      });
    });

Full-page `position:fixed` iframe – hiding the address bar on mobile when scrolling down within iframe, like for top-level scroll

Question:

On mobile (in some browsers) when you scroll down, the user agent has some sort of heuristic for hiding the browser address bar. This is nice because it gives more screen real estate “for free”.

I have a situation where I’m embedding a ~fullscreen (other than a header/menu bar) iframe in order to sandbox user-written code (think CodePen/JSBin/etc), and I’d like to take advantage of this browser address bar hiding feature if at all possible.

Extra context:

  • I’m in control of the top-level page, and can inject code into the embedded iframe (but note that they’re cross-origin in case that’s relevant).
  • I’m willing to get quite hacky with my solution (e.g. involving postMessage between frames) if it would result in an end result that is quite robust – i.e. unlikely to randomly break scrolling/whatever in some browsers, under some conditions (e.g. user pinches to zoom on page), or after some valid update to the heuristic, etc. If it works in some browsers, but automatically/safely falls back to not having any effect in unsupported, then that’s fine.
  • Any “interventions” within the iframe shouldn’t interfere with the user code in a way that is likely to be relevant to the vast majority of web apps. E.g. a postMessage to the parent is fine, since it is very unlikely to interfere with user code.
  • Probably not relevant, but the iframe is thread/performance isolated with Origin-Agent-Cluster.

Non-Solutions:

  • Making the iframe as tall as its content is not a solution, since this would result in an abnormal visual viewport size, which would affect user code that e.g. visually centers their content within the viewport, or relies on properties like window.innerHeight (and CSS vh) for calculations.
  • Adding fullscreen button is not a solution, but it does offer one alternative that could suit some use cases.
  • Running the user code at the top level (with its own subdomain) is not a solution, since I need the parent frame for important platform-level functionality.

Attempted Solutions:

I’m not optimistic that this is currently possible to achieve, given the set of requirements that I’ve outlined above.

  1. My first thought was that I could just programmatically scroll the top-level frame in sync with the child frame (using postMessage from the child), such that the address bar would naturally hide itself when they’d scrolled the child frame far enough. But unfortunately (in Android Chrome, at least), the user agent does not hide the address bar based on programmatic scrolling – probably for security/anti-deception reasons.

  2. My second thought was that I’d have to tell the embedded iframe to set overflow:hidden; on document.scrollingElement, so that the overscroll triggers the parent frame scroll, which triggers the user agent to hide the address bar, and then maybe I could detect that with Visual Viewport API, and tell the iframe to re-enable scrolling. Even if that would work, this is definitely pushing the limits of the “do not interfere with user code” rule. Ideally it would be the parent that decides that the iframe is not scrollable until the address bar has disappeared. But there’s also the problem of knowing if the address bar will actually disappear at all, and when it will start to disappear, since I don’t think the address bar hiding happens right away – this complicates things a lot.

So, it seems like you’d need something extremely hacky to get this working. I’m hoping that there’s eventually be a browser-standards-supported way of doing this, and part of my reason for posting this question despite being quite pessimistic is so that I’ll hopefully get notified when it does become possible.

Making a map in highcharts using velocity

I am trying to make a map in velocity for my chart that is rendered through the highcharts API. I have many following methods, and none seem to work. My first example is what I want to see. The rest are just random tests.

#set($queryArray = 
    {
        "name" : "Approved", 
        "query" : "test"
    },
    {
        "name" : "Proposed", 
        "query" : "test"
    },
    {
        "name" : "Draft", 
        "query" : "test"
    },
    {
        "name" : "Blank", 
        "query" : "test"
    }
)

The error for the above ‘map’ is as such: Uncaught SyntaxError: Unexpected token ‘<‘,
Leading me here:

var options = <span class="polarion-rp-widget-warning" style="display:block;"><i class="fa fa-warning"></i>There was an exception (see server log for details) Encountered "n" at line 12, column 20.
Was expecting one of:
    "[" ...
    "(" ...
    <STRING_LITERAL> ...
    "true" ...
    "false" ...
    <NUMBER_LITERAL> ...
    <IDENTIFIER> ...
    "{" ...
    "!" ...
    </span>;

Now, for my next attempt at a map:

#set($queries)
#set($queries.Map = {"banana" : "good", "roast beef" : "bad"})

The error for the above ‘map’ is as such: Uncaught SyntaxError: Unexpected token ‘<‘,
Leading me here:

var options = <span class="polarion-rp-widget-warning" style="display:block;"><i class="fa fa-warning"></i>There was an exception (see server log for details) Encountered ")n" at line 12, column 14.
Was expecting one of:
    <WHITESPACE> ...
    "=" ...
    <DOT> ...
    </span>;

My last map attempt:

#set($queryMap = $objectFactory.newMap)
$queryMap.put("Dog")

The error for the above ‘map’ is as such: Uncaught ReferenceError: $queryMap is not defined,
Leading me here:

$queryMap.put("Dog")

I am quite lost, as these are the only methods for a map in velocity that I saw posted on the internet. Documentation was not very helpful but maybe I missed something. Help would be most appreciated.

Web Worker Thread Pool

I have developed a Javascript Excel Add-in that uses a Web Worker to make background / long-running service API requests. The user determines how many requests need to be made, and the results are then written to a worksheet in the workbook. This works fine, however as the number of requests increases the serice API provider can get overwhelmed.

Ideally I would like to have some sort of thread pool of Web Workers that could process the API requests from a queue – per the following example in Java:

https://www.baeldung.com/thread-pool-java-and-guava

Executor Service

The number of worker threads could be configured by the user based upon the API service provider capabilities.

Based upon a search of the site I cannot find any precedent, and would appreciate thoughts.

Cheers,
Andrew

I have problem with dragging elements in html

I am making page like google maps with html, css, javascript so I want to make page draggable.

        let newX = 0, newY = 0, startX = 0, startY = 0;

        const map = document.getElementsByClassName('world-map')[0]

        map.addEventListener('mousedown', mouseDown)

        function mouseDown(e) {
            startX = e.clientX
            startY = e.clientY

            document.addEventListener('mousemove', mouseMove)
            document.addEventListener('mouseup', mouseUp)
        }

        function mouseMove(e){
        newX = startX - e.clientX 
        newY = startY - e.clientY 
    
        startX = e.clientX
        startY = e.clientY

        map.style.left = startX + 'px'
        map.style.top = startY + 'px'

        }
        
        function mouseUp(e) {
            document.removeEventListener('mousemove', mouseMove)
        }

I tried this but it moves back to start point(0,0) after mouseup and then

        let newX = 0, newY = 0, startX = 0, startY = 0;

        const map = document.getElementsByClassName('world-map')[0]

        map.addEventListener('mousedown', mouseDown)

        function mouseDown(e) {
            startX = e.clientX
            startY = e.clientY

            document.addEventListener('mousemove', mouseMove)
            document.addEventListener('mouseup', mouseUp)
        }

        function mouseMove(e){
        newX = startX - e.clientX 
        newY = startY - e.clientY 
    
        startX = e.clientX
        startY = e.clientY

        map.style.top = (map.offsetTop - startY) + 'px'
        map.style.left = (map.offsetLeft - startX) + 'px'

        }
        
        function mouseUp(e) {
            document.removeEventListener('mousemove', mouseMove)
        }

tried this but it doesn’t even move.

Element world-map’s css is ‘position:absolute’

I think I need to update a new x,y in variables after moving so tried several ways but it doesn’t worked.
Is there any possible way to make it?
Sorry for my bad english.

is it possible to build a local website that can access a .db file and dynamically update pages without a webserver?

I have a .db file made using sqlite that contains information about stories that were scraped from the internet (title, author, summary, file path, .etc).

I plan for all the story files to be in one folder and then use the database to show them on html webpages and what not.

Like a page with a list of authors, and when you click an authors name, it would go to a page with a list of stories, and it would access the database to get that information.

It would only be on something that’s run on my computer, not connected to the internet or anything so I don’t want a server. The reason why i would like it ot be serverless because i want my friends to use the program without having to worry about trying to set up a server or anything.

i know php can interact with sql but it seems to need a sever, and i know there’s some java script libraies that can work with sql, but i’m not sure if js can access the files or create the necessary pages

Honestly am just looking where to start. I just want to be able to click on a link and see what stories were saved.

Closure Javascript. Why I can’t get access to the inner variable if it is returned

const crateCounter = () => {
  let count = 0 

  const increment = () => {
    count++
  }
  const getCount = () => {
    return count
  }
  return { increment, getCount, count }
}

let counter = crateCounter()

counter.increment() // count is 1
counter.increment() // count is 2
counter.increment() // count is 3
console.log(counter.getCount()) // showing 3. Good!
console.log(counter.count) // showing 0. Why?

Why the method getCount() get access to the variable count but why we cannot access to the variable count itself?

Question: Smooth Scrolling and Snap-to-Section Issues in Horizontal Scrollable Portfolio Website

I am developing a personal portfolio website with a top horizontal header and a horizontally scrollable content wrapper below it. Problem: when clicking on links the scrolling isn’t smooth. Also, the snap functionality doesn’t always work.

I want to achieve the following:

Smooth scrolling: When a user clicks on a navigation link in the header, the page should smoothly scroll to the corresponding section.
Snapping behavior: When the user manually scrolls horizontally, the page should snap to the nearest section, ensuring the sections don't end up partially visible.

Here is the relevant code I have so far:

document.querySelectorAll('nav a').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
        e.preventDefault();
        const targetId = this.getAttribute('href');
        const targetSection = document.querySelector(targetId);
        const contentWrapper = document.querySelector('.content-wrapper');
        const offsetLeft = targetSection.offsetLeft;

        contentWrapper.scrollTo({
            left: offsetLeft,
            behavior: 'smooth'
        });
    });
});

const contentWrapper = document.querySelector('.content-wrapper');
let isScrolling;

contentWrapper.addEventListener('scroll', () => {
    window.clearTimeout(isScrolling);

    isScrolling = setTimeout(() => {
        const sections = document.querySelectorAll('.content section');
        const scrollPosition = contentWrapper.scrollLeft + contentWrapper.offsetWidth / 2;

        let closestSection = sections[0];
        let closestDistance = Math.abs(scrollPosition - closestSection.offsetLeft);

        sections.forEach(section => {
            const distance = Math.abs(scrollPosition - section.offsetLeft);
            if (distance < closestDistance) {
                closestSection = section;
                closestDistance = distance;
            }
        });

        closestSection.scrollIntoView({
            behavior: 'smooth',
            block: 'nearest',
            inline: 'start'
        });
    }, 100);
});
.main {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.content-wrapper {
    height: 80vh;
    overflow-x: auto;
    overflow-y: hidden;
    scroll-snap-type: x mandatory;
    position: fixed;
    top: 20vh;
    width: 100%;
    scroll-behavior: smooth;
}

.content {
    display: flex;
    height: 100%;
}

.content section {
    flex: 0 0 100vw;
    scroll-snap-align: start;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.section-content {
    padding: 20px;
    background-color: rgb(69, 63, 189);
    border-radius: 10px;
    text-align: center;
    width: 80vw;
}

<div class="main">
        <div class="header">
            <div class="headerWrap">
                <div class="info">
                    <h1>Arnaud Ducoulombier</h1>
                    <h2>Full Stack Developer</h2>
                    <p>Motivated learner in the web industry</p>
                </div>
                <nav>
                    <ul>
                        <li><a href="#about">About</a></li>
                        <li><a href="#skills">Skills</a></li>
                        <li><a href="#projects">Projects</a></li>
                    </ul>
                </nav>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="content">
                <section id="about">
                    <div class="section-content">
                        <h3>About Me</h3>
                        <p>This is the about section.</p>
                    </div>
                </section>
                <section id="skills">
                    <div class="section-content">
                        <h3>My Skills</h3>
                        <p>This is the skills section.</p>
                    </div>
                </section>
                <section id="projects">
                    <div class="section-content">
                        <h3>My Projects</h3>
                        <p>This is the projects section.</p>
                    </div>
                </section>
            </div>
        </div>