Webpack 5: Can’t get my webpack.config.js file setup to Handle Multiple HTML pages

I have a project using HTML, CSS, and JS which I’m trying to use webpack 5 to build separate folders for /pages and /posts for HTML, a folder for my json files (/json-files), and separate folders/files for CSS, /media, /json-files and bundle.js.  All CSS references are in the HTML files (1 HTML file per page).  My directory structure is as follows:

index.html (home page)

    /pages (all my web HTML pages)    /posts (all my blogs HTML pages)    /stylesheets (all my CSS)    /scripts (all my custom js code with the exception of server.js and webpack.config.js)    /json-files (all my json files used by my custom js code)    /media (all my jpg, png, SVG, and MP4 files)

and all the other supporting files (e.g., package.json, node_modules, webpack.config.js, …).  These folders have subfolders as well.  This is very different than the course material.

The build process works without errors or warnings, and the webpack build does create folders /pages and /posts with my HTML, /media, and /JSON-files which seem to contain all the files (flat folder with all files into).

However, none of <link> and <script> have been removed from the HTML files.  I can manually delete them from the HTML files and site works, but they appear to be using my files in my project root (not from /build).

My project can be seen https://github.com/mmelester/intensivehope.com.git .

I’ve been fighting this for a week now.  Any guidance would be appreciated.  This is my wife’s site, and I need to get her off my back.  This is my very first website.

I’ve tried countless webpack.config.js implementations, and this is the closest I got to working. I’ve even taken a couple of Udemy webpack courses but they all are centered around js code building out the pages with all CSS coming from the js.

What is the current code for inserting github icon?

I used to insert the github icon into my work but it didn’t show. How do I achieve that?

I tried using to insert the github icon into my work but it didn’t show. How do I achieve that? Please I need help as soon as possible so that I can finish and submit an assignment I was given. Thanks.

How to test case for the line document.body.dispatchEvent() in react js

I want to check if document.dispatchEvent is fired when we called sendEvent method. I also want to write negative test case like when we called sendEvent method, document.body.dispatchEvent should not fire. I need some help in writing testcase.

// evt = "pageview" data={page: {name: "someName"}}
sendEvent=(evt, data)=>{
  if(document.createEvent && document.body.dispatchEvent){
    const event= document.createEvent('Event');
    event.initEvent(evt, true, true);
    event.detail = data;
    document.body.dispatchEvent(event);
  } 
}

//testcase

test("test document triggred an event", ()={
global.document.createEvent = jest.fn();
global.document.body.dispatchEvent = jest.fn();

sendEvent("pageName", {page: {name: "someName"}});
expect(global.document.body.dispatchEvent).toHaveBeenCalledWith(Event);

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

Cannot upload file in using component (“Failed to set the ‘value’ property on ‘HTMLInputElement'”)

I’m receiving the console error DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string. when trying to upload a file using the <calcite-input> Calcite Design Component. However, no issues when using the normal <input> HTML element with the same attributes.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Calcite Design System -->
    <script type="module" src="https://js.arcgis.com/calcite-components/2.8.0/calcite.esm.js" integrity="sha384-YlUxwaQ8HMbpzggbtila0Yu/pQOahe1f79e6x6eN+H+Om1KPWOc7L0EQeYauqXrk" crossorigin="anonymous"></script>
    <link rel="stylesheet" type="text/css" href="https://js.arcgis.com/calcite-components/2.8.0/calcite.css" />

    <title>Test</title>
</head>
<body>
    <form id="test-form" action="/" method="POST" enctype="multipart/form-data">
        <calcite-input type="file" name="calcite_input_file" accept=".xlsx"></calcite-input> <!-- throws error in console, file not sent in request -->
        <input type="file" name="input_file" accept=".xlsx" /> <!-- no errors, file sent in request -->
        <button form="test-form" type="submit">Submit</button>
    </form>
</body>
</html>

Tried switching from Calcite Design Components v 2.7.0 to 2.8.0 but issue persists. Can just use the normal <input> HTML element and add my own styling to match the Calcite Design Components look, but would like to avoid that extra work 😀 hoping I’m just missing a required attribute for <calcite-input> file uploads or setting something up wrong.

Pre-increment by more than 1 (JavaScript)

Is there a version of the += operator that pre-increments?

I understand pre- and post- increment in JS (i++ and ++i), and I also am aware of i += n if I want to increment by n, but to my understanding the += operator is a post-increment. If I want to do an inline pre-increment by more than 1, which operator would I use? Is this possible?

Currently, my approach is to simply increment the variable on another line, but doing this inline would be nice!

How can I create an object with the value the result from an api call?

Good evening,

I am currently trying to create an object that will contain:

{
  "acct_123": [
   // result from calling stripe api 
  ],
  "acct_456": [
   // result from calling stripe api 
  ]
}

The parameter of my function is the list of stripeIds: ['acct_123', 'acct_456']

I tried this:

const fetchList = async (id: string) => {
    const resp = await stripe.accounts.listExternalAccounts(
        id,
        { object: "bank_account" },
        { apiKey }
     )
    return resp.data;
 }

const bankAccoutFetchPromises: any = [];
stripeConnectAccountIds.map(async (id: string) => {
      const bankAccountList = await stripe.accounts.listExternalAccounts(
        id,
        { object: "bank_account" },
        { apiKey }
      );
      bankAccoutFetchPromises.push(bankAccountList.data);
 });
Promise.all(bankAccoutFetchPromises);

Unfortunately this call only fetch the data for the first element in the array. 😐

Can you please help me with setting object key the id and the value the result from fetchList(id)?

Thanks! 🙂

How to use matter.js on a web worker?

I want to use matter.js on a web worker with offscreen canvas, but the problem is it seems to throw errors about requestAnimationFrame. It tries to get it by using window.requestAnimationFrame but in a web worker window is not defined. Also if I try to set a sprite, it fails because matter.js uses new Image() but that isn’t defined in a web worker. Also it tries to style the canvas, but that doesn’t work since its an offscreen canvas.

Has anyone gotten this to work?

ajax request failing with “TypeError: Cannot read properties of undefined (reading ‘open’)”

Feel like I’m missing something obvious (I don’t work with javascript or jQuery, I’m just playing around with it in my spare time), but I can’t figure out why my ajax request won’t work – can’t find the answer anywhere on google either.

When I try an ajax request with the below code, it fails with the error: ajax request failing with “TypeError: Cannot read properties of undefined (reading ‘open’)” – it doesn’t even hit my api endpoint

$.ajax({
        url: window.location.origin + "/api/test",
        type: "GET",
        dataType: "json",
        cache: false,
        contentType: "application/json"
    })
        .done(function (json) {
            conole.log(json);
        })
        .fail(function (xhr, status, error) {
            console.log(xhr);
            console.log(status);
            console.log(error);
        });

If I do it with vanilla javascript, it works fine:

var r = await fetch(window.location.origin + "/api/test", {
        method: "GET"
    });

I’ve tried messing around with all kinds of properties in the ajax request, but to no avail. What am I missing?

Why does my JavaScript code not update the weather information on the webpage?

I am developing a weather forecast web application using HTML, CSS, and JavaScript. The application is supposed to fetch weather data from a backend service and display it dynamically on the page, but the weather information is not being updated as expected. Here is the relevant part of my JavaScript and Java code:

package weatherController;

import weather.Weather;
import weatherService.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class WeatherController {

    @Autowired
    private WeatherService weatherService;

    @GetMapping("/weather/{city}")
    public Weather getWeatherForCity(@PathVariable String city) {
        return weatherService.getWeather(city);
    }
}
package weatherService;



import weather.Weather;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class WeatherService{

    @Value("${api.weather.key}")
    private String apiKey;

    private static final String WEATHER_URL = "http://api.weatherapi.com/v1/current.json";

    @GetMapping("/weather")
    public Weather getWeather(@RequestParam String city) {
        String url = String.format("%s?key=%s&q=%s", WEATHER_URL, apiKey, city);
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(url, Weather.class);
    }
}
import conditions from './conditions.js';

console.log(conditions);


const header = document.querySelector('.header');
const form = document.querySelector('#form');
const input = document.querySelector('#inputCity');


function removeCard() {
    const prevCard = document.querySelector('.card');
    if (prevCard) prevCard.remove();
}


function showError(errorMessage) {
    const html = `<div class="card">${errorMessage}</div>`;
    header.insertAdjacentHTML('afterend', html);
}


function showCard({ name, country, temp, condition, imgPath }) {
    const html = `<div class="card">
        <h2 class="card-city">${name} <span>${country}</span></h2>
        <div class="card-weather">
            <div class="card-value">${temp}<sup>°C</sup></div>
            <img class="card-img" src="${imgPath}" alt="Weather">
        </div>
        <div class="card-description">${condition}</div>
    </div>`;
    header.insertAdjacentHTML('afterend', html);
}


async function getWeather(city) {
    const url = `http://localhost:8080/weather?city=${encodeURIComponent(city)}`;
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
    return data;
}


form.onsubmit = async function (e) {
    e.preventDefault();
    let city = input.value.trim();
    const data = await getWeather(city);

    if (data.error) {
        removeCard();
        showError(data.error.message);
    } else {
        removeCard();
       
        const info = conditions.find(obj => obj.code === data.current.condition.code);
        const filePath = './img/' + (data.current.is_day ? 'day' : 'night') + '/';
        const fileName = (data.current.is_day ? info.day : info.night) + '.png';
        const imgPath = filePath + fileName;
        
        const weatherData = {
            name: data.location.name,
            country: data.location.country,
            temp: data.current.temp_c,
            condition: data.current.condition.text,
            imgPath
        };

        showCard(weatherData); 
    }
};
  1. Ensuring the backend API is returning the correct JSON data.

  2. Checking that all DOM elements (input, form, and .card) exist in the HTML.

  3. Confirming there are no console errors related to fetching or parsing data.

How to handle “auth/popup-closed-by-user” + COOP firebase errors?

recently I’ve been trying to familiarize myself with Firebase authentication, and I made a simple React app that allows for a Google sign in and sign out (displaying the account name in the console upon successful sign in.) Everything works fine, but if I close out of the Google sign in popup at any time, I get this error in the console: “FirebaseError: Firebase: Error (auth/popup-closed-by-user)”. The error is self explanatory, but I’m new to web dev and wondering how I would actually handle this “error” in my code? I honestly would’ve figured closing out of the popup would do absolutely nothing. I have a try/catch to console log the error but how on earth am I supposed to handle this to prevent the console from filling up with error messages? It seems like closing out of a sign in popup is a pretty common thing for a user to do..

Do errors like this normally flood the console and we just ignore them do to already having a try/catch in our source code? I’m OCD and having a console full of red makes me feel like I’m already making wrong development choices, lol. I’ve attached a screenshot of my console showing that error, along with COOP errors/cookie warnings that are being presented. Are these various errors/warnings all just Firebase specific things? Thanks in advance to anyone who can offer me some support!

enter image description here

My main component code:

import { GoogleLoginButton } from "react-social-login-buttons";
import { auth, googleProvider } from "../config/firebase.js";
import { signInWithPopup, signOut } from "firebase/auth";

export const Auth = () => {

    const signInWithGoogle = async () => {
        try {
            await signInWithPopup(auth, googleProvider);
        } catch (err) {
            console.log(err);
        }
        console.log(auth?.currentUser?.displayName); // display Google account name 
    }

    const userLogout = async () => {
        console.log("logout clicked");
        try {
            await signOut(auth);
        } catch (err) {
            console.log(err);
        }
        console.log(auth?.currentUser?.displayName); // (should always be undefined) 
    }

    return (
        <div>
            <GoogleLoginButton onClick={ signInWithGoogle }>
                <span>Sign in with Google</span>
            </GoogleLoginButton>
            <button onClick = { userLogout }>Sign Out</button>
        </div>
    )
}

ERR_CONNECTION_REFUSED After deploying Angular app to Render.com

My deployed render app is not able to get the backend data. I also cannot try to login or register.

Opening the app in firefox rather than chrome shows another error: “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/foods. (Reason: CORS request did not succeed). Status code: (null).”

Link to app: https://food-store-angular.onrender.com/

Github link: https://github.com/dannyj172/Food-Store-Angular/

Image of console errors

Vue, nuxt useFetch is stacking calls

I have quite a simple code, where I call getData() function onMounted and than I call this function on some emited events. getData function just call useApi composable. But every time I call getData() function the data are fetched more and more times (If I call getData 6 times i get 6 calls at once). Wierd thing is that the function is called just once (when I put for example console.log in it it is called once, but data fetch is stacking calls). This is how it looks like – first component mounted = data fetched once, first emit call = data fetched twice, second emit = data fetched three times:
Stacking calls

The code:

<template>
  
    <PageSection title="Uživatelé" :footerLink="{to: '#', text: 'Administrace uživatelů'}">
      <DataTable  :isLoading="isLoading" :columns="columns" :pageSize="query.pageSize" :pagination="users.pagination" @pageSizeChange="handlePageSizeChange" @search="handleSearch" @pageChange="handlePageChange">
        <tr v-for="user in users.data" :key="user._id">
          <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
            <div>
              {{ user.email }}
            </div>
            <div class="text-[.65rem]">
              {{ user._id }}
            </div>
          </td>
          <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
            <span v-for="role in user.roles">{{ role.name }}</span>
          </td>
          <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{{ new Date(user.createdAt).toLocaleDateString(undefined, dateOptions) }}</td>
          <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{{ new Date(user.updatedAt).toLocaleDateString(undefined, dateOptions) }}</td>
        </tr>
      </DataTable>
      <div v-if="users.error">Error</div>
    </PageSection>
  </template>
  
  <script setup>
    definePageMeta({
      title: 'Administrace'
    })
    
    const columns = ['Uživatel', 'Role', 'Vytvořeno', 'Změněno']
    
    const users = ref([])
    const isLoading = ref(true)

    const apiUrl = '/api/v1/private/users'
    const query = ref({page: 1, pageSize: 10, search: ''})

    onMounted(async () => {
        await getData()
    })

    const getData = async () => {
      users.value = []
      isLoading.value = true
      users.value = await useApi(apiUrl, {
        method: 'GET',
        query: query
      })
      isLoading.value = false
    }

    const handlePageSizeChange = async (newPageSize) => {
      query.value = {...query.value, pageSize: newPageSize}
      await getData()
    }

    const handlePageChange = async (pageClicked) => {
      query.value = {...query.value, page: pageClicked}
      await getData()
    }

    const handleSearch = async (searchQuery) => {
      query.value = {...query.value, search: searchQuery}
      await getData()
    }

    const dateOptions = {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
      seconds: 'numeric'
    }

  </script>

useApi composable:

const { refreshToken } = useAuthStore()
var pagination = {}
var error = null
export const useApi = async (url , options) => {
    const { data, error } = await useFetch(`http://localhost:3001${url}`, {...options, credentials: 'include', retry: 1, retryStatusCodes: [401],
        async onResponse({ request, response, options }) {
            pagination = {
                recordsTotal: response.headers.get('X-Records-Total'),
                pageSize: response.headers.get('X-Page-Size'),
                pageCurrent: response.headers.get('X-Page-Current'),
                pageTotal: response.headers.get('X-Page-Total'),
                linkNextPage: response.headers.get('X-Link-Next-Page'),
                linkPreviousPage: response.headers.get('X-Link-Previous-Page'),
                linkLastPage: response.headers.get('X-Link-Last-Page')
            }
        }, 
        async onResponseError({request, response, options}){
            if (response.status === 401 && response._data.authenticationToken) {
                await refreshToken(response._data.authenticationToken)
                return
            } else if (response.status === 401){
                console.log('Přihlášení vypršelo')
                window.location.reload()
            }
            throw response
        },
        async onRequest({ request, options }) {
            options.headers = options.headers || {};
            options.headers.accept = 'application/json';
            const { authenticationToken } = useAuthStore()
            if (authenticationToken) {
                options.headers.authorization = `Bearer ${authenticationToken}`;
            }
        },
        async onRequestError({ request, options, error }) {
            console.log('[fetch request error]')
        }
    })
    return {
        data: data,
        pagination: pagination,
        error: error
    }      
}

Can someone tell me, what am I missing?

ScrollY always returns 0 unless DevTools is open

I’m working on a web project where I have a scroll-triggered animation. The bar charts in a graph are supposed to pop up when the user reaches a certain point. The animations aren’t happening as expected because scrollY is always returning 0 unless DevTools is open when I load the page.

https://pith.gotbdev.com/

HTML:

<div id="bar-chart" class="chart">
    <div class="chart-section" data-sales="50">
        <img src="/wp-content/uploads/Bill-Clinton.png" alt="Product Image">
        <div class="bar"></div>
    </div>
    <!-- Repeat for other products -->
</div>

CSS:

#bar-chart {
    width: 100%;  /* Full width to contain horizontally laid out content */
    overflow: hidden;  /* Hide overflowing content horizontally */
    position: relative;
}

.chart-section {
    display: flex;  /* Use flexbox for horizontal layout */
    align-items: center;  /* Center items vertically within each section */
    justify-content: flex-start;  /* Align content to the start of the flex container */
    width: 100%;  /* Full width for each section */
    height: 100%;  /* Full viewport height for each section */
    visibility: hidden;  /* Start with sections hidden */
    position: relative;  /* Position sections relative within the container */
    transition: opacity 1s ease-in-out;  /* Smooth transition for appearing */
    opacity: 0;  /* Start fully transparent */
}

.chart-section img {
    width: 300px;  /* Fixed width for images */
    margin-right: 20px;  /* Space between the image and the bar */
    z-index:2;
}

.bar {
    margin-left:-10vw;
    z-index:1;
    height: 50px;  /* Fixed height for bars */
    width: 0;  /* Start with zero width */
    background: -webkit-radial-gradient(circle, #ecc373 0%, #e7c872 40%, #dab681 60%, #c69d50 100%);
    
}

JS:

    document.addEventListener('DOMContentLoaded', function() {
    const sections = document.querySelectorAll('.chart-section');
    const topSection = document.querySelector('.elementor-top-section');
    let animationStarted = false;

    function startAnimation() {
        console.log("Animation started");
        if (!animationStarted) {
            sections.forEach((section, index) => {
                const bar = section.querySelector('.bar');
                const sales = section.dataset.sales;
                bar.style.width = `${sales}%`;  // Animate the width of the bar based on sales data
                section.style.opacity = '1'; // Make the section visible
                                section.style.visibility = 'visible'; // Make the section visible
            });
            animationStarted = true;
        }
    }

    function checkScroll() {
        const scrollThreshold = topSection.offsetTop + topSection.clientHeight; // Set scroll threshold to the bottom of the top section
        const scrollY = window.scrollY;

        if (scrollY > scrollThreshold) {
            console.log("Scroll threshold reached");
            startAnimation();
            window.removeEventListener('scroll', checkScroll); // Remove the scroll event listener once animation started
        }
    }

    window.addEventListener('scroll', checkScroll);
});

I’ve made sure that overflow is set to visible on the HTML and body.

Seeking advice on how to resolve the issue with scrollY returning 0.

Summary: I attempted to implement a scroll-triggered animation on my website using JavaScript. I expected the animation to trigger smoothly as the user scrolled down the page, with elements becoming visible and adjusting dynamically based on the scroll position. However, I encountered an issue where the scrollY property always returned 0 unless DevTools was open. The animation only works when DevTools is active, leading to inconsistent behavior.

Oracle Apex Double Horizontala Scrollbar on Classic Report

Have a page with a faceted search region + a classic report with a basic query.
I’m trying to add a second scrollbar on top so user has two (one at top, another in bottom).
Using this code to no avail, anyone has any idea?
(report Static Id ‘admin’)

JS:

function DoubleScroll(element) {
  var scrollbar = document.createElement('div');
  scrollbar.appendChild(document.createElement('div'));
  scrollbar.style.overflow = 'auto';
  scrollbar.style.overflowY = 'hidden';
  scrollbar.firstChild.style.width = element.scrollWidth+'px';
  scrollbar.firstChild.style.paddingTop = '1px';
  scrollbar.firstChild.appendChild(document.createTextNode('xA0'));
  scrollbar.onscroll = function() {
      element.scrollLeft = scrollbar.scrollLeft;
  };
  element.onscroll = function() {
      scrollbar.scrollLeft = element.scrollLeft;
  };
  element.parentNode.insertBefore(scrollbar, element);
}

DoubleScroll(document.getElementById('admin'));

CSS:

#admin {overflow: auto; overflow-y: hidden;}

Thanks

webkitSpeechRecognition keep listening always without ask for more than one permission

I am using webkitSpeechRecognition to my app, but after some time it stops, and I need that keep listening all the time, how can I do that?.

I have watched examples through internet, but they are old and the most of them have an implementation like this function that starts again

recognition.onend = function(event){
    recognition.start();
}

I use it, but always that I finish to speak I need to give permission in the browser.

enter image description here

I don’t know if by browser politics I need to give permission always that I use my microphone.